Problem
Given a sorted array of numbers, find if a given number key
is present in the array. Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order.
Example
Example 1:
|
|
Example 2:
|
|
Solution
This approach is similar to binary search, but we must first determine if the array is sorted in ascending or descending order. This distinction is essential for deciding whether to search the lower or upper half of the array.
We begin with two pointers, start
and end
, to define our search space, initially set to 0
and n-1
, respectively.
- First, we compare the
key
with the middle element. - If the array is ascending and the
key
is less than the middle element, or if the array is descending and thekey
is greater than the middle element, we search the lower half (end = mid - 1
). - Otherwise, the search continues in the upper half (
start = mid + 1
).
We can determine the sorting order by comparing the elements at the beginning and the end of the array:
|
|
Method 1 - Iterative Implementation
|
|
Method 2 - Recursive Implementation
|
|
Complexity
- ⏰ Time complexity:
O(log n)
- 🧺 Space complexity:
O(1)