The method begins by setting lowerBound andupperBound variables to the first and

last occupied cells in the array.

We also define mid variable variable mid which points to middle position of array.

Setting these variables specifies the range where the item we’re looking for, key, can be found.

If mid points to the desired item, so we first check if this is true. If it is, we’ve found the item, so we return with mid(as it is position at which we have found element).

Each time through the loop we divide the range in half. Ultimately, the range will get so small that it can’t be divided any more. We check this in the next statement-

If lowerBound is greater than upperBound (Element has not been found and we return).

If mid is not pointing at the desired item, and the range is still big enough, we’ll divide the range in half. We compare the value at the current index, a[mid], which is in the middle of the range, with the value to be found i.e. key.

Now there can be 2cases>

Case1>

If key is larger, we know we should look in the upper half of the range.

Accordingly, we move lowerBound up to mid. Actually, we move it one cell beyond

mid because we’ve already checked mid itself at the beginning of the loop.

Case2>

If key is smaller than a[mid], we know we should look in the lower half of

the range. So we move upperBound down to one cell below mid.

Full Program/SourceCode >

/**

*This class holds reference of array, in which data has to be searched.

Complexity of Binary Search is O(logN), where N is number of elements.

It doesn't half search time, that wouldn't make it log(n). It decreases it logarithmically.

If you had 128 entries in a table and had to search linearly for your value, it would probably take around 128 entries on average to find your value. That's log(n) or linear time.

With a binary search, you eliminate 1/2 the possible entries each iteration, such that at most it would only take 7 compares to find your value (log base 2 of 128 is 7 or 2 to the 7 power is 128.) This is the power of binary search.

Comparisons needed in Binary Search >

Searching 10 item in Binary search will take average of 4 searches.

Searching 100 item in Binary search will take average of 7 searches.

Searching 1000 item in Binary search will take average of 10 searches & so on….