Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confuse in Binary Search when to use left < right ; left <= right ; and few more

I've difficulty in understanding when to use:

while (left < right ) {
}

vs when to use:

while (left <= right ) {
}

Also while setting left and right boundaries sometimes we use:

left = mid 

and sometime we use

left = mid + 1;

similarly

right = mid; vs
right = mid - 1;

Is there any fundamental I am missing in knowledge of Binary search ?

like image 486
Ankit Kotak Avatar asked Jul 25 '19 04:07

Ankit Kotak


People also ask

Does binary search go left or right?

Here is how we search in a binary search tree: Begin at the tree's root node. If the value is smaller than the current node, move left. If the value is larger than the current node, move right.

What is the special condition for binary search?

The precondition for binary search is that the array should be sorted. If the data is not sorted, we can't apply binary search on that array.

When can you not use a binary search?

In case the list of elements is not sorted, there's no way to use binary search because the median value of the list can be anywhere and when the list is split into two parts, the element that you were searching for could be cut off.


2 Answers

The basic idea is to search and find the element:

public static int indexOf(int[] array, int target) {
   int lo = 0, hi = a.length - 1;
   while (lo <= hi) {
      // Key is in a[lo..hi] or may be it is not present.
      int mid = lo + (hi - lo) / 2;
      if      (target < a[mid]) hi = mid - 1;
      else if (target > a[mid]) lo = mid + 1;
      else return mid;
   }
   return -1;
}

We can also use mid = (lo + hi) >>> 1 to compute the mid but using (lo+hi)/2 may cause overflow. Now the confusion part:

We use while (lo <= hi) if we are returning the match from inside the loop. We use while (lo < hi) when we want to exit the loop first and then use the result of lo or hi to return the match.

like image 161
akhil_mittal Avatar answered Sep 28 '22 01:09

akhil_mittal


When you divide an array you find the mid index. At this time you have two parts with a mid index. Since the array is sorted you compare the search element with mid index value.

If the search value is smaller than mid index value you know it is at left side otherwise it is at right side.

Now, you repeat the above step (divide into two parts, mid index etc.) for either left half (index 0 to mid - 1) or right half (index mid +1 to end). If the search value is same as mid index value then element is found and you stop processing.

This divide and compare process continues until you find the search element or left and right index (initially 0 and length-1) overlaps. Thats why the condition left <= right.

like image 31
fiveelements Avatar answered Sep 28 '22 03:09

fiveelements