Binary Search
Binary Search
In Binary Search, the array is divided into two equal halves. The search value is then checked whether the value in the mid
element of the array is the search value or not. If not, then it is checked whether the search value is on the lower end or the
upper end of the array. The array is continuously divided till the number is found or not.
Binary Search takes place by dividing the array into two equal halves till the number is found or not
It is a faster process than linear search
It is suitable when the volume of data is large
It can be performed on an arranged or a sorted array only.
It can be performed on a unique array only (no duplicate elements).
To divide the array into two halves, we have to make the two ends of the array meet.
The lower end is known as the lower bound (lb) of the array which is always 0 unless otherwise specified.
The upper end is known as the upper bound (ub) of the array which is always n-1, where n is the number of elements in the
array. So if there are 50 elements, then the upper bound will be (50-1),that is 49.
Once we know the lower bound (lb) and the upper bound (ub), we have to find the middle or mid bound using the formula:
mb = (lb + ub)/2
0 1 2 3 4 5 6 7 8 9
3 5 7 11 13 15 21 24 31 36
Step 1
lb=0,ub=9
mb =(lb+ub)/2
=(0+9)/2
=4
So the element in the mid bound is 4 (a[4]=13)
Now let us check whether the number in the mid element is equal to the search vallue or not
That means the value in the mid bound is not the search value
Now let us check whether the search value is on the lower half or upper half
if(a[mb], that is 13<31) (true)
lb=mb+1
Since 31 is on the upper half, we know that there is no need in searching of the value in the lower half
So we reduce the array now from index 5 to 9
5 6 7 8 9
15 21 24 31 36