I know this question is very trivial to ask, but I have got some doubt while solving this problem.Code is given below
public class BinarySearch {
public static int binSearch(int a[], int x) { // a is sorted
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (x < a[mid])
high = mid - 1;
else if (x > a[mid])
low = mid + 1;
else
return mid;
}
return Integer.MIN_VALUE;
}
If we want to calculate the worst case comparisons of binary search,then
it will be $2 \log n+1$, because $\log n+1$ for checking (low<=high)
and $\log n$ for (x < a[mid])
or if (x > a[mid])
.
Alright , i have no issue here , i can happily say that worst case comparison for Binary search is $2\log n +1$
I faced issue when i tried to solve the recurrence equation, given as-:
$$T(n)=T(\frac{n}{2})+1$$
$\text{Base Case}\,\,T(1)=1$
$T(\frac{n}{2})=T(\frac{n}{4})+1$
Generalizing the equation i got-:
$T(n)=T(\frac{n}{2^{k}})+1+1..+1(k \text{times})$
$T(n)=T(\frac{n}{2^{k}})+k$
$\frac{n}{2^k}=1$
$k=\log n$
So $T(n)=\log n+1$ What actually this value signifies? Is it Minimum number of comparison? Confused Please help me out