Binary Search is an efficient algorithm to find a target value within a sorted array. The idea is to repeatedly divide the search interval in half.
Pseudocode:
Binary_Search(arr, target)
1. Set low = 0, high = length(arr) - 1
2. While low ≤ high:
a. mid = (low + high) / 2
b. If arr[mid] == target:
Return mid (found the target at index mid)
c. Else if arr[mid] < target:
Set low = mid + 1 (search in the right half)
d. Else:
Set high = mid - 1 (search in the left half)
3. If not found, return -1
Explanation:
- We begin by setting two pointers:
low
andhigh
. - We calculate the middle of the array (
mid
). - If the middle element matches the target, we return its position.
- Otherwise, if the middle element is less than the target, we adjust the
low
pointer to narrow down the search to the right half. - If the middle element is greater than the target, we adjust the
high
pointer to focus on the left half. - The loop continues until either the element is found or the search space is exhausted.
0 Comments