-
Input: Receive a sorted array
arrof 10 elements and a numbernumto be searched. -
Initialize: Set
firstto 0 (the index of the first element) andlastto 9 (the index of the last element). Calculatemiddleas the average offirstandlast. -
Binary Search Loop:
- Enter a
whileloop as long asfirstis less than or equal tolast. - Check the middle element:
- If it is less than
num, updatefirsttomiddle + 1. - If it is equal to
num, print the position and exit the loop. - If it is greater than
num, updatelasttomiddle - 1.
- If it is less than
- Recalculate
middlebased on the updatedfirstandlast.
- Enter a
-
Output:
- If
firstis greater thanlast, the numbernumis not found in the array. - Print the result.
- If
-
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.