-
Input: Receive a sorted array arr
of 10 elements and a number num
to be searched.
-
Initialize: Set first
to 0 (the index of the first element) and last
to 9 (the index of the last element). Calculate middle
as the average of first
and last
.
-
Binary Search Loop:
- Enter a
while
loop as long as first
is less than or equal to last
.
- Check the middle element:
- If it is less than
num
, update first
to middle + 1
.
- If it is equal to
num
, print the position and exit the loop.
- If it is greater than
num
, update last
to middle - 1
.
- Recalculate
middle
based on the updated first
and last
.
-
Output:
- If
first
is greater than last
, the number num
is not found in the array.
- Print the result.
-
End: The program ends, returning 0.
In essence, binary search works by repeatedly dividing the search interval in half. If the middle element is equal to the target, the search is successful. If the middle element is less than the target, the search continues in the right half; otherwise, it continues in the left half. This process repeats until the target is found or the search interval is empty.