I don't know js but I know Java so I'm presenting my implementation of binary search using for loop as follows:
int bSearch(int arr[],int x) {
int index = 0;
for(int i = arr.length >> 1; i >= 1; i>>=1)
while((index + i < arr.length) && (arr[index + i] <= x))
index+=i;
return(arr[index] == x) ? index : -1;
}
How it works??
Consider i as mid and index as lower bound of binary search.
If u notice carefully, you'll find that in binary search, everytime the mid starts with arr.length divided by 2 and after every iteration, it gets divided by 2 and a last step, it reaches it's minimum value i.e. 1.
So in for loop I've implemented the same.
But those who are wondering what is:
int i = arr.length >> 1;
It actually means:
int i = arr.length / 2;
And same for
i>>=1
It is same as:
i /= 2; or i = i / 2;
Now at the while loop part, the first condition checks that if we add index with i , will it go out of the boundary of array or not. The second condition checks whether x lies in between index(lower bound) and i (mid). If it's true then we don't need to add index with i but if it's not the case then :
x lies after i(mid) so we are adding index(lower bound) with i(mid).
This part of code highlighted in traditional binary search:
int bSearch(int arr[], int x) {
int lowerBound = 0;
int upperBound = array.length - 1;
while (left <= right) {
int middle = (lowerBound + upperBound) / 2;
if (array[middle] == x)
return middle;
// *look at this condition carefully*
if (x > array[middle])
lowerBound = middle + 1;
else
upperBound = middle - 1;
}
return -1;
}
Notice the following line:
if(x > arr[middle])
lowerBound = middle + 1;
The above code can be also written as:
if(arr[middle + lowerBound] <= x)
lowerBound += middle;
Now if x is present in the array and array is sorted then index should have the index of x and return it else otherwise, it will return -1.
val > middleshould beval > arr[middle].if(val > middle)?