Performance of
Binary Search: O(logN)
private int recFind(long searchKey, int lowerBound, int upperBound)
{
int curIn;
curIn = (lowerBound + upperBound)/2;
if (a[curIn] == searchKey)
return curIn;
else if (lowerBound > upperBound)
return nElems;
else
{
if (a[curIn] < searchKey)
return recFind(searchKey, curIn+1, upperBound);
else
return recFind(searchKey, lowerBound, curIn-1);
} // end else
} //end recFind()
The above recursive method works as a binary search. Suppose that the number of nodes in a binary tree is N. In other words, the problem size is initially N. Then, whenever a comparison has been done, the problem size which is needed to be considered becomes a half of the previous problem size.
Problem size
N
After 1 comparison
N/2
After 2 comparison
N/22
After 3 comparison
N/23
After 4 comparison
¡¦
After L comparison
N/2L
A comparison will be continued until our problem size becomes 1. Since the time complexity of this algorithm is equivalent of the number of comparison, we can find out the time complexity by calculating the number L in terms of N.
Thus, N/2L = 1
N
= 2L
log N = log 2L ©¬ Base 2 Logarithm
log N = L
* log 2 ©¬ log22 = 1
L = log N
è O(log N)