Question

000111: Find the first occurrence of 1 in the best way possible. This was all the...

000111: Find the first occurrence of 1 in the best way possible.

This was all the information and details I was given for the question.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

  • The input given is {0,0,0,1,1,1}(lets say an array with 0,1,2,3,4,5 indexes) out of which we have to findout the index of the first occurence of 1.
  • When you search linearly from the left to right, it takes 4 comparisons to find the 1.
  • You can obeserve that the list is already sorted. So we can apply binary search insted of linear search.
  • Binary search finds out the middle element first then it compares the required element with middle element.
  • Here, middle element will be (0+5)/2=2 where, 5 is the total length of the input[0th element, 1st element,......,5th element]. middle element=(lower limit+upper limit)/2
  • So it compares 2nd element with 1.In this case actually the 2nd element is 0.
  • So apply binary search on right elements of 2nd elements {1,1,1} to which the upper limit= 5 and lowe limit = 3, middle element is (5+3)/2=4. And the fourth element is 1. But there is possiblity that it might not be the first 1.
  • Then take 4th element as upper limit, and 3rd element as lower limit then the middle element will be 4+2/2=3. And which is 1 the first occurace of 1.
  • So if you use binary search it take only 3 comparision to get there.
  • In a larger view/ input linear search takes n comparisions where as binary takes logn comparisons.

Implementation:

Code:

#include <stdio.h>
int code1(int input[], int ll, int ul);
int main()
{
int input[] = { 0, 0, 0, 1, 1, 1};
   int n = sizeof(input)/sizeof(input[0]);
   printf("%d",code1(input,0,n - 1));
   return 0;
}
int code1(int input[], int ll, int ul)//ll=lower limit, ul=upperlimit
{
   while (ll <= ul) {
       int middle=(ll+ul)/2;
       if (input[middle]==1&&(middle==0||input[middle-1]==0))
           return middle;
       else if (input[middle]==1)
           ul=middle-1;
       else
           ll=middle+1;
   }
   return -1;
}

Output:

Add a comment
Know the answer?
Add Answer to:
000111: Find the first occurrence of 1 in the best way possible. This was all the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT