Suppose the 16 elements are sorted in the array 3, 22, 30, 33, 40, 44, 50, 60, 66, 78, 88, 99. Apply the binary search to search the value 50 from the sorted array.
Q.) Suppose the 16 elements are sorted in the array 3, 22, 30, 33, 40, 44, 50, 60, 66, 78, 88, 99. Apply the binary search to search the value 50 from the sorted array.
Subject: Data StructuresBinary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.
Here is how we can apply binary search to find the value 50 in the sorted array [3, 22, 30, 33, 40, 44, 50, 60, 66, 78, 88, 99].
Initialize: Start by initializing two pointers,
low
andhigh
.low
is initialized to the start of the array (index 0), andhigh
is initialized to the end of the array (index 11 in this case).low = 0 high = 11
Find the middle: Calculate the middle index of the array using the formula
mid = low + (high - low) / 2
. In our case,mid
will be5
(integer value of 5.5).mid = 0 + (11 - 0) / 2 = 5.5
So,
mid
is5
. The element at index5
is44
.Compare: Compare the middle element with the target value (
50
).
- If the middle element is equal to the target, we have found the target in the array. Return the index.
- If the middle element is greater than the target, the target can only lie in the first half of the array. So, we update high
to mid - 1
.
- If the middle element is less than the target, the target can only lie in the second half of the array. So, we update low
to mid + 1
.
In our case, 44
is less than 50
, so we update low
to mid + 1
, which is 6
.
- Repeat: Repeat steps 2 and 3 until
low
is not greater thanhigh
.
- Calculate mid
again: mid = 6 + (11 - 6) / 2 = 8.5
. So, mid
is 8
. The element at index 8
is 66
.
- 66
is greater than 50
, so we update high
to mid - 1
, which is 7
.
- Calculate mid
again: mid = 6 + (7 - 6) / 2 = 6.5
. So, mid
is 6
. The element at index 6
is 50
.
- 50
is equal to 50
. We have found the target at index 6
.
So, the value 50
is found at index 6
in the array.
Here is a table summarizing each step:
Step | low | high | mid | Array[mid] | Action |
---|---|---|---|---|---|
1 | 0 | 11 | 5 | 44 | low = mid + 1 |
2 | 6 | 11 | 8 | 66 | high = mid - 1 |
3 | 6 | 7 | 6 | 50 | Found at index 6 |
This is how binary search works. It is an efficient search algorithm as it has a time complexity of O(log n), where n is the number of elements in the array.