Binary Search

Its a problem of the logic in binary search
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int binarySearch ( double array[], 
			double itemToFind, 	int size) 
{
  int bottom = 0;  
  int top = size -1;
  int middle = (bottom + top) /2;
  bool found = false;
  

while ((bottom <= top) && (found == false))  {
     if (array[middle] == itemToFind)
        found = true;
     else     
     {
       if (array [middle] > itemToFind)
           top = middle -1;
       else  
           bottom = middle + 1;
        middle = (bottom + top) /2;
     }  
  }
  if (found == false)
     return -1;
  else
     return middle;
} 


So , in while condition while ((bottom <= top) && (found == false))


I know why there are two conditions in the while loop , but my question is will it be an infinite loop or the loop wont run if we drop one of those ?
Line 12 could have been return midde; and then the found variable is not needed.

If you have this
middle = (bottom + top) /2;
between lines 10 and 11 you can giveup on line 19 and drop the = (bottom + top) /2 in the definition on line 6.
You can give up on this one (bottom <= top) Only if your sure the item your looking for is in the array. If it's not there you'll get an infinite loop.
Topic archived. No new replies allowed.