Hi,
what is the index of the search key if we search for 24 in the following array using binary search.
array = [10,20,21,24,24,24,24,24,30,40,45]
As pointed out by @Pleepleus it will return the index 5 from the first level of recursion itself. However I would like to point out few things about binary search :
mid = (left + right)/2
, use mid = left + (right-left)/2
If you want to search for lower_bound
or upper_bound
of an element use the following algorithms:
binLowerBound(a, lo, hi, x)
if (lo > hi)
return lo;
mid = lo + (hi - lo) / 2;
if (a[mid] == x)
return binLowerBound(a, lo, mid-1, x);
else if (a[mid] > x)
return binLowerBound(a, lo, mid-1, x);
else
return binLowerBound(a, mid+1, hi, x);
binHigherBound(a, lo, hi, x)
if (lo > hi)
return lo;
mid = lo + (hi - lo) / 2;
if (a[mid] == x)
return binHigherBound(a, mid+1, hi, x);
else if (a[mid] > x)
return binHigherBound(a, lo, mid-1, x);
else
return binHigherBound(a, mid+1, hi, x);