Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this tutorial, we’ll discuss searching for a number in a sorted and rotated array. We’ll define the problem and provide an example to explain it.
After that, we’ll present an elegant approach to solving it.
Given an integer, , and a sorted rotated array,
, consisting of distinct integers, our task is to find the element’s position whose value equals
in
. If there’s no such element, we return
.
Let’s take a look at the following example:

Assume we want to find the following numbers in the given array:
The main idea is to use the binary search technique to find the position of in
. If we’re currently looking at the value at position
, we’ll encounter three different cases:
In the end, if we finish the binary search and don’t return any value during the search, then our target doesn’t exist in
. As a result, we return
.
Let’s take a look at the implementation:
algorithm BinarySearchApproach(A, X):
// INPUT
// A = a sorted and rotated array of distinct integers
// X = the integer to find in the array
// OUTPUT
// The position of X in A if found; otherwise -1
low <- 0
high <- length(A) - 1
while low <= high:
middle <- (low + high) / 2
if A[middle] = X:
return middle
else if A[middle] < X:
if A[low] > A[middle] and A[low] <= X:
high <- middle - 1
else:
low <- middle + 1
else:
if A[high] < A[middle] and A[high] >= X:
low <- middle + 1
else:
high <- middle - 1
return -1
The implementation uses the exact ideas described in section 3.1.
The complexity of this algorithm is , where
is the length of the given array
. The reason behind this complexity is the same as the binary search complexity, where we keep dividing the given array each time into two halves and looking for the target in one of them.
This article presented the most efficient way to find an integer in a sorted rotated array. First, we provided an example of the problem. Then we gave an elegant approach to solving it and walked through its implementation.