The problem is to find the index of a target value within a sorted array of integers. The constraint that the array is
sorted allows us to utilize a binary search algorithm, which is known for its O(log N)
runtime complexity. This
efficiency is achieved by repeatedly dividing the search interval in half until the target value is found or the
interval is empty.
The binary search algorithm works as follows:
- Initialize Pointers: Start with two pointers,
leftIndex
at the beginning (0) andrightIndex
at the end ( length of the array - 1). - Iterative Search:
- Calculate the middle index of the current search interval.
- Compare the target value with the middle element of the array.
- If the target is equal to the middle element, return the middle index.
- If the target is less than the middle element, narrow the search interval to the left half by moving the
rightIndex
tomiddleIndex - 1
. - If the target is greater than the middle element, narrow the search interval to the right half by moving the
leftIndex
tomiddleIndex + 1
.
- Termination: The loop terminates when
leftIndex
exceedsrightIndex
, indicating the target is not in the array . In this case, return-1
.
- Time Complexity:
O(log N)
: Binary search repeatedly divides the search interval in half, leading to a logarithmic time complexity. - Space Complexity:
O(1)
: The algorithm uses a constant amount of extra space for the pointers and the middle index calculation.