'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 ?
Solution 1:[1]
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.
Solution 2:[2]
use left <= right when you are changing the mid index in the loop
mid = right -1
mid = left +1
use left < right when you are assigning the left and right directly to mid
right = mid
left = mid+1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
