Search in a Sorted and Rotated Array
Last Updated :
23 Jul, 2025
Given a sorted and rotated array arr[] of n distinct elements, the task is to find the index of given key in the array. If the key is not present in the array, return -1.
Examples:
Input: arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 3], key = 3
Output: 8
Explanation: 3 is present at index 8 in arr[].
Input: arr[] = [3, 5, 1, 2], key = 6
Output: -1
Explanation: 6 is not present in arr[].
Input: arr[] = [33, 42, 72, 99], key = 42
Output: 1
Explanation: 42 is found at index 1.
[Naive Approach] Using Linear Search - O(n) Time and O(1) Space
A simple approach is to iterate through the array and check for each element, if it matches the target then return the index, otherwise return -1. To know more about the implementation, please refer Introduction to Linear Search Algorithm.
[Expected Approach 1] Using Binary Search Twice - O(log n) Time and O(1) Space
The idea is to use binary search twice:
1. Find the pivot point (or index of the min element) : For example, the min in [4, 5, 6, 7, 0, 1, 2] is 0 at index 4. Refer Minimum in a Sorted and Rotated Array to find the index of the minimum element.
2. Binary Search in the Sorted Subarray: Once we find the pivot, we can easily divide the given array into two sorted subarrays using the index of the minimum element. For example, the index of the minimum element in [4, 5, 6, 7, 0, 1, 2] is 4, so the two sorted subarrays are [4, 5, 6, 7] and [1, 2]. Following are the cases that arise
- If the minimum element = key, then return index of the minimum element.
- If index of minimum element is 0, then the whole array is sorted, we call binary search for the whole array.
- If index of minimum element > 0, then instead of calling binary search for both sides, we can save one binary search by comparing the given key with the first element on left side. If key is greater than equal to the first element, we do binary search in the first subarray else in the second.
C++
// C++ program to search an element in sorted and rotated
// array using binary search twice
#include <iostream>
#include <vector>
using namespace std;
// An iterative binary search function
int binarySearch(vector<int> &arr, int lo, int hi, int x) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// Function to return pivot (index of the smallest element)
int findPivot(vector<int> &arr, int lo, int hi) {
while (lo < hi) {
// The current subarray is already sorted,
// the minimum is at the low index
if (arr[lo] <= arr[hi])
return lo;
int mid = (lo + hi) / 2;
// The right half is not sorted. So
// the minimum element must be in the
// right half.
if (arr[mid] > arr[hi])
lo = mid + 1;
// The right half is sorted. Note that in
// this case, we do not change high to mid - 1
// but keep it to mid. The mid element
// itself can be the smallest
else
hi = mid;
}
return lo;
}
// Searches an element key in a pivoted
// sorted array arr of size n
int search(vector<int> &arr, int key) {
int n = arr.size();
int pivot = findPivot(arr, 0, n - 1);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
// If the minimum element is present at index
// 0, then the whole array is sorted
if (pivot == 0)
return binarySearch(arr, 0, n - 1, key);
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
int main() {
vector<int> arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int key = 3;
cout << search(arr, key);
return 0;
}
C
// C program to search an element in sorted and rotated
// array using binary search twice
#include <stdio.h>
// An iterative binary search function
int binarySearch(int arr[], int lo, int hi, int x) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// Function to return pivot (index of the smallest element)
int findPivot(int arr[], int lo, int hi) {
while (lo < hi) {
// The current subarray is already sorted,
// the minimum is at the low index
if (arr[lo] <= arr[hi])
return lo;
int mid = (lo + hi) / 2;
// The right half is not sorted. So
// the minimum element must be in the
// right half.
if (arr[mid] > arr[hi])
lo = mid + 1;
// The right half is sorted. Note that in
// this case, we do not change high to mid - 1
// but keep it to mid. The mid element
// itself can be the smallest
else
hi = mid;
}
return lo;
}
// Searches an element key in a pivoted
// sorted array arr of size n
int search(int arr[], int n, int key) {
int pivot = findPivot(arr, 0, n - 1);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
// If the minimum element is present at index
// 0, then the whole array is sorted
if (pivot == 0)
return binarySearch(arr, 0, n - 1, key);
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
int main() {
int arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 3;
printf("%d\n", search(arr, n, key));
return 0;
}
Java
// Java program to search an element in sorted and rotated
// array using binary search twice
import java.util.*;
class GfG {
// An iterative binary search function
static int binarySearch(int[] arr, int lo, int hi, int x) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// Function to return pivot (index of the smallest element)
static int findPivot(int[] arr, int lo, int hi) {
while (lo < hi) {
// The current subarray is already sorted,
// the minimum is at the low index
if (arr[lo] <= arr[hi])
return lo;
int mid = (lo + hi) / 2;
// The right half is not sorted. So
// the minimum element must be in the
// right half
if (arr[mid] > arr[hi])
lo = mid + 1;
// The right half is sorted. Note that in
// this case, we do not change high to mid - 1
// but keep it to mid. The mid element
// itself can be the smallest
else
hi = mid;
}
return lo;
}
// Searches an element key in a pivoted
// sorted array arr of size n
static int search(int[] arr, int key) {
int n = arr.length;
int pivot = findPivot(arr, 0, n - 1);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
// If the minimum element is present at index
// 0, then the whole array is sorted
if (pivot == 0)
return binarySearch(arr, 0, n - 1, key);
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
public static void main(String[] args) {
int[] arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int key = 3;
System.out.println(search(arr, key));
}
}
Python
# Python program to search an element in sorted and rotated
# array using binary search twice
# An iterative binary search function
def binarySearch(arr, lo, hi, x):
while lo <= hi:
mid = lo + (hi - lo) // 2
if arr[mid] == x:
return mid
if arr[mid] < x:
lo = mid + 1
else:
hi = mid - 1
return -1
# Function to return pivot (index of the smallest element)
def findPivot(arr, lo, hi):
while lo < hi:
# The current subarray is already sorted,
# the minimum is at the low index
if arr[lo] <= arr[hi]:
return lo
mid = (lo + hi) // 2
# The right half is not sorted. So
# the minimum element must be in the
# right half.
if arr[mid] > arr[hi]:
lo = mid + 1
# The right half is sorted. Note that in
# this case, we do not change high to mid - 1
# but keep it to mid. The mid element
# itself can be the smallest
else:
hi = mid
return lo
# Searches an element key in a pivoted
# sorted array arr of size n
def search(arr, key):
n = len(arr)
pivot = findPivot(arr, 0, n - 1)
# If we found a pivot, then first compare with pivot
# and then search in two subarrays around pivot
if arr[pivot] == key:
return pivot
# If the minimum element is present at index
# 0, then the whole array is sorted
if pivot == 0:
return binarySearch(arr, 0, n - 1, key)
if arr[0] <= key:
return binarySearch(arr, 0, pivot - 1, key)
return binarySearch(arr, pivot + 1, n - 1, key)
if __name__ == "__main__":
arr = [5, 6, 7, 8, 9, 10, 1, 2, 3]
key = 3
print(search(arr, key))
C#
// C# program to search an element in sorted and rotated
// array using binary search twice
using System;
class GfG {
// An iterative binary search function
static int binarySearch(int[] arr, int lo, int hi, int x) {
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// Function to return pivot (index of the smallest element)
static int findPivot(int[] arr, int lo, int hi) {
while (lo < hi) {
// The current subarray is already sorted,
// the minimum is at the low index
if (arr[lo] <= arr[hi])
return lo;
int mid = (lo + hi) / 2;
// The right half is not sorted. So
// the minimum element must be in the
// right half.
if (arr[mid] > arr[hi])
lo = mid + 1;
// The right half is sorted. Note that in
// this case, we do not change high to mid - 1
// but keep it to mid. The mid element
// itself can be the smallest
else
hi = mid;
}
return lo;
}
// Searches an element key in a pivoted
// sorted array arr of size n
static int search(int[] arr, int key) {
int n = arr.Length;
int pivot = findPivot(arr, 0, n - 1);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] == key)
return pivot;
// If the minimum element is present at index
// 0, then the whole array is sorted
if (pivot == 0)
return binarySearch(arr, 0, n - 1, key);
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
static void Main(string[] args) {
int[] arr = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };
int key = 3;
Console.WriteLine(search(arr, key));
}
}
JavaScript
// JavaScript program to search an element in sorted and rotated
// array using binary search twice
// An iterative binary search function
function binarySearch(arr, lo, hi, x) {
while (lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
if (arr[mid] === x) return mid;
if (arr[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// Function to return pivot (index of the smallest element)
function findPivot(arr, lo, hi) {
while (lo < hi) {
// The current subarray is already sorted,
// the minimum is at the low index
if (arr[lo] <= arr[hi])
return lo;
let mid = Math.floor((lo + hi) / 2);
// The right half is not sorted. So
// the minimum element must be in the
// right half.
if (arr[mid] > arr[hi])
lo = mid + 1;
// The right half is sorted. Note that in
// this case, we do not change high to mid - 1
// but keep it to mid. The mid element
// itself can be the smallest
else
hi = mid;
}
return lo;
}
// Searches an element key in a pivoted
// sorted array arr of size n
function search(arr, key) {
let n = arr.length;
let pivot = findPivot(arr, 0, n - 1);
// If we found a pivot, then first compare with pivot
// and then search in two subarrays around pivot
if (arr[pivot] === key)
return pivot;
// If the minimum element is present at index
// 0, then the whole array is sorted
if (pivot === 0)
return binarySearch(arr, 0, n - 1, key);
if (arr[0] <= key)
return binarySearch(arr, 0, pivot - 1, key);
return binarySearch(arr, pivot + 1, n - 1, key);
}
// Driver code
let arr = [5, 6, 7, 8, 9, 10, 1, 2, 3];
let key = 3;
console.log(search(arr, key));
[Expected Approach 2] Using Single Binary Search - O(log n) Time and O(1) Space
The idea is based on the fact that in a sorted and rotated array, if we go to mid, then either the left half would be sorted or the right half (both can also be sorted). For example, arr[] = [5, 6, 0, 1, 2, 3, 4], mid = 3 and we can see that the subarray from mid + 1 to high is sorted. And in [5, 6, 7, 8, 9, 3, 4], we can see that the subarray from low to mid-1 is sorted. We can check which half is sorted by comparing arr[low] and arr[mid] (We could also compare arr[high] and arr[mid]).
- Find the mid point. If key is same as the mid, return the mid.
- Find which half is sorted. If the key lies in the sorted half, move to that half. Otherwise move to the other half.
Note that once we find which half is sorted, we can easily check if the key lies here by checking if key lies in the range from smallest to largest in this half.
C++
// C++ program to search an element in sorted and rotated
// array using binary search
#include <iostream>
#include <vector>
using namespace std;
int search(vector<int>& arr, int key) {
// Initialize two pointers, lo and hi, at the start
// and end of the array
int lo = 0, hi = arr.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If key found, return the index
if (arr[mid] == key)
return mid;
// If Left half is sorted
if (arr[mid] >= arr[lo]) {
// If the key lies within this sorted half,
// move the hi pointer to mid - 1
if (key >= arr[lo] && key < arr[mid])
hi = mid - 1;
// Otherwise, move the lo pointer to mid + 1
else
lo = mid + 1;
}
// If Right half is sorted
else {
// If the key lies within this sorted half,
// move the lo pointer to mid + 1
if (key > arr[mid] && key <= arr[hi])
lo = mid + 1;
// Otherwise, move the hi pointer to mid - 1
else
hi = mid - 1;
}
}
// Key not found
return -1;
}
int main() {
vector<int> arr1 = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int key1 = 3;
cout << search(arr1, key1) << endl;
return 0;
}
C
// C program to search an element in sorted and rotated
// array using binary search
#include <stdio.h>
int search(int arr[], int n, int key) {
// Initialize two pointers, lo and hi, at the start
// and end of the array
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If key found, return the index
if (arr[mid] == key)
return mid;
// If Left half is sorted
if (arr[mid] >= arr[lo]) {
// If the key lies within this sorted half,
// move the hi pointer to mid - 1
if (key >= arr[lo] && key < arr[mid])
hi = mid - 1;
// Otherwise, move the lo pointer to mid + 1
else
lo = mid + 1;
}
// If Right half is sorted
else {
// If the key lies within this sorted half,
// move the lo pointer to mid + 1
if (key > arr[mid] && key <= arr[hi])
lo = mid + 1;
// Otherwise, move the hi pointer to mid - 1
else
hi = mid - 1;
}
}
// Key not found
return -1;
}
int main() {
int arr1[] = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int key1 = 3;
printf("%d\n", search(arr1, n1, key1));
return 0;
}
Java
// Java program to search an element in sorted and rotated
// array using binary search
import java.util.*;
class GfG {
static int search(int[] arr, int key) {
// Initialize two pointers, lo and hi, at the start
// and end of the array
int lo = 0, hi = arr.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If key found, return the index
if (arr[mid] == key)
return mid;
// If Left half is sorted
if (arr[mid] >= arr[lo]) {
// If the key lies within this sorted half,
// move the hi pointer to mid - 1
if (key >= arr[lo] && key < arr[mid])
hi = mid - 1;
// Otherwise, move the lo pointer to mid + 1
else
lo = mid + 1;
}
// If Right half is sorted
else {
// If the key lies within this sorted half,
// move the lo pointer to mid + 1
if (key > arr[mid] && key <= arr[hi])
lo = mid + 1;
// Otherwise, move the hi pointer to mid - 1
else
hi = mid - 1;
}
}
// Key not found
return -1;
}
public static void main(String[] args) {
int[] arr1 = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int key1 = 3;
System.out.println(search(arr1, key1));
}
}
Python
# Python program to search an element in sorted and rotated
# array using binary search
def search(arr, key):
# Initialize two pointers, lo and hi, at the start
# and end of the array
lo = 0
hi = len(arr) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
# If key found, return the index
if arr[mid] == key:
return mid
# If Left half is sorted
if arr[mid] >= arr[lo]:
# If the key lies within this sorted half,
# move the hi pointer to mid - 1
if key >= arr[lo] and key < arr[mid]:
hi = mid - 1
# Otherwise, move the lo pointer to mid + 1
else:
lo = mid + 1
# If Right half is sorted
else:
# If the key lies within this sorted half,
# move the lo pointer to mid + 1
if key > arr[mid] and key <= arr[hi]:
lo = mid + 1
# Otherwise, move the hi pointer to mid - 1
else:
hi = mid - 1
# Key not found
return -1
if __name__ == "__main__":
arr1 = [5, 6, 7, 8, 9, 10, 1, 2, 3]
key1 = 3
print(search(arr1, key1))
C#
// C# program to search an element in sorted and rotated
// array using binary search
using System;
class GfG {
static int search(int[] arr, int key) {
// Initialize two pointers, lo and hi, at the start
// and end of the array
int lo = 0, hi = arr.Length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
// If key found, return the index
if (arr[mid] == key)
return mid;
// If Left half is sorted
if (arr[mid] >= arr[lo]) {
// If the key lies within this sorted half,
// move the hi pointer to mid - 1
if (key >= arr[lo] && key < arr[mid])
hi = mid - 1;
// Otherwise, move the lo pointer to mid + 1
else
lo = mid + 1;
}
// If Right half is sorted
else {
// If the key lies within this sorted half,
// move the lo pointer to mid + 1
if (key > arr[mid] && key <= arr[hi])
lo = mid + 1;
// Otherwise, move the hi pointer to mid - 1
else
hi = mid - 1;
}
}
// Key not found
return -1;
}
static void Main(string[] args) {
int[] arr1 = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };
int key1 = 3;
Console.WriteLine(search(arr1, key1));
}
}
JavaScript
// JavaScript program to search an element in sorted and rotated
// array using binary search
function search(arr, key) {
// Initialize two pointers, lo and hi, at the start
// and end of the array
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
let mid = lo + Math.floor((hi - lo) / 2);
// If key found, return the index
if (arr[mid] === key)
return mid;
// If Left half is sorted
if (arr[mid] >= arr[lo]) {
// If the key lies within this sorted half,
// move the hi pointer to mid - 1
if (key >= arr[lo] && key < arr[mid])
hi = mid - 1;
// Otherwise, move the lo pointer to mid + 1
else
lo = mid + 1;
}
// If Right half is sorted
else {
// If the key lies within this sorted half,
// move the lo pointer to mid + 1
if (key > arr[mid] && key <= arr[hi])
lo = mid + 1;
// Otherwise, move the hi pointer to mid - 1
else
hi = mid - 1;
}
}
// Key not found
return -1;
}
// Driver code
let arr1 = [5, 6, 7, 8, 9, 10, 1, 2, 3];
let key1 = 3;
console.log(search(arr1, key1));
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem