Binary Search Algorithm
Suppose there is an array, array = {1,5,7,8,13,19,20,23,29}.
Now we need to search for the location of item 23.
![]() |
Binary Search Algorithm Explained |
Let us consider low is the lowest index position, mid is the center index position and high is the possible highest index position i.e. 0, 4, and 8 respectively at first.
In First Step:
low = 0, mid = (low + high)/2 = (0 + 8)/2 = 4, high = 8
a [mid] = a [4] = 13 since 13 is less than 23 so,
In Second Step:
low = mid + 1 = 4 + 1 = 5, high = 8, mid = 13/2 = 6
a [mid] = a [6] = 20 since 20 is also less than 23 so again,
In Third Step:
low = mid + 1 = 6 + 1 = 7, high = 8, mid = 15/2 = 7 since 7.5 is not
considered
a [mid] = a [7] = 23 i.e. a searched item of an array. The index of that item is 7.
In the context of a binary search algorithm, at first, a condition is set that checks whether the given array has some value or not.
If not, then integer -1 is returned otherwise the first value to be searched is compared with the middle value.
If the value matches while comparing, then the index number of that particular array is returned otherwise that array is fragmented into two halves.
Before fragmenting the array, the value is properly checked whether it is smaller than the middle value or greater.
As the array is sorted, either the value is compared to the array having a starting index number greater than the index number of the middle value or to the array having the last index number smaller than the index number of middle values.
This process occurs repeatedly until and unless the searched value is identified or the lowest index number is smaller than the highest index number.
0 Comments
Feel Free To Ask Any Queries?