# Search an element in a sorted and rotated Array

• Difficulty Level : Medium
• Last Updated : 08 Aug, 2022

Given a sorted and rotated array arr[] of size N and a key, the task is to find the key in the array.

Note: Find the element in O(logN) time and assume that all the elements are distinct.

Example:

Input  : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}, key = 3
Output : Found at index 8

Input  : arr[] = {5, 6, 7, 8, 9, 10, 1, 2, 3}, key = 30

Input : arr[] = {30, 40, 50, 10, 20}, key = 10
Output : Found at index 3

Recommended Practice

Approach 1 (Finding Pivot where rotation has happened): The primary idea to solve the problem is as follows.

The idea is to find the pivot point, divide the array into two sub-arrays and perform a binary search.

The main idea for finding a pivot is –

• For a sorted (in increasing order) and rotated array, the pivot element is the only element for which the next element to it is smaller than it.
• Using binary search based on the above idea, pivot can be found.
• It can be observed that for a search space of indices in range [l, r] where the middle index is mid
• If rotation has happened in the left half, then obviously the element at l will be greater than the one at mid.
• Otherwise the left half will be sorted but the element at mid will be greater than the one at r.
• After the pivot is found divide the array into two sub-arrays.
• Now the individual sub-arrays are sorted so the element can be searched using Binary Search.

Follow the steps mentioned below to implement the idea:

• Find out the pivot point using binary search. We will set the low pointer as the first array index and high with the last array index.
• From the high and low we will calculate the mid value.
• If the value at mid-1 is greater than the one at mid, return that value as the pivot.
• Else if the value at the mid+1 is less than mid, return mid value as the pivot.
• Otherwise, if the value at low position is greater than mid position, consider the left half. Otherwise, consider the right half.
• Divide the array into two sub-arrays based on the pivot that was found.
• Now call binary search for one of the two sub-arrays.
• If the element is greater than the 0th element then search in the left array
• Else search in the right array.
• If the element is found in the selected sub-array then return the index
• Else return -1.

Follow the below illustration for a better understanding

Illustration:

Consider arr[] = {3, 4, 5, 1, 2}, key = 1

Pivot finding:

low = 0, high = 4:
=>  mid = 2
=>  arr[mid] = 5, arr[mid + 1] = 1
=> arr[mid] > arr[mid +1],
=> Therefore the pivot = mid = 2

Array is divided into two parts {3, 4, 5}, {1, 2}
Now  according to the conditions and the key, we need to find in the part {1, 2}

Key Finding:

We will apply Binary search on {1, 2}.
low = 3 , high = 4.
=>  mid = 3
=>  arr[mid] = 1 , key = 1, hence arr[mid] = key matches.
=>  The required index = mid = 3

So the element is  found at index 3.

Below is the implementation of the above approach:

## C++

 `// C++ Program to search an element` `// in a sorted and pivoted array`   `#include ` `using` `namespace` `std;`   `// Standard Binary Search function` `int` `binarySearch(``int` `arr[], ``int` `low, ``int` `high, ``int` `key)` `{` `    ``if` `(high < low)` `        ``return` `-1;`   `    ``int` `mid = (low + high) / 2;` `    ``if` `(key == arr[mid])` `        ``return` `mid;`   `    ``if` `(key > arr[mid])` `        ``return` `binarySearch(arr, (mid + 1), high, key);`   `    ``return` `binarySearch(arr, low, (mid - 1), key);` `}`   `// Function to get pivot. For array 3, 4, 5, 6, 1, 2` `// it returns 3 (index of 6)` `int` `findPivot(``int` `arr[], ``int` `low, ``int` `high)` `{` `    ``// Base cases` `    ``if` `(high < low)` `        ``return` `-1;` `    ``if` `(high == low)` `        ``return` `low;`   `    ``// low + (high - low)/2;` `    ``int` `mid = (low + high) / 2;` `    ``if` `(mid < high && arr[mid] > arr[mid + 1])` `        ``return` `mid;`   `    ``if` `(mid > low && arr[mid] < arr[mid - 1])` `        ``return` `(mid - 1);`   `    ``if` `(arr[low] >= arr[mid])` `        ``return` `findPivot(arr, low, mid - 1);`   `    ``return` `findPivot(arr, mid + 1, high);` `}`   `// Searches an element key in a pivoted` `// sorted array arr[] of size n` `int` `pivotedBinarySearch(``int` `arr[], ``int` `n, ``int` `key)` `{` `    ``int` `pivot = findPivot(arr, 0, n - 1);`   `    ``// If we didn't find a pivot,` `    ``// then array is not rotated at all` `    ``if` `(pivot == -1)` `        ``return` `binarySearch(arr, 0, n - 1, key);`   `    ``// 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` `(arr <= key)` `        ``return` `binarySearch(arr, 0, pivot - 1, key);`   `    ``return` `binarySearch(arr, pivot + 1, n - 1, key);` `}`   `// Driver program to check above functions` `int` `main()` `{` `    ``// Let us search 3 in below array` `    ``int` `arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };` `    ``int` `n = ``sizeof``(arr1) / ``sizeof``(arr1);` `    ``int` `key = 3;`   `    ``// Function calling` `    ``cout << ``"Index of the element is : "` `         ``<< pivotedBinarySearch(arr1, n, key);`   `    ``return` `0;` `}`

## C

 `/* Program to search an element in` `   ``a sorted and pivoted array*/` `#include `   `int` `findPivot(``int``[], ``int``, ``int``);` `int` `binarySearch(``int``[], ``int``, ``int``, ``int``);`   `/* Searches an element key in a pivoted` `   ``sorted array arrp[] of size n */` `int` `pivotedBinarySearch(``int` `arr[], ``int` `n, ``int` `key)` `{` `    ``int` `pivot = findPivot(arr, 0, n - 1);`   `    ``// If we didn't find a pivot,` `    ``// then array is not rotated at all` `    ``if` `(pivot == -1)` `        ``return` `binarySearch(arr, 0, n - 1, key);`   `    ``// 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` `(arr <= key)` `        ``return` `binarySearch(arr, 0, pivot - 1, key);` `    ``return` `binarySearch(arr, pivot + 1, n - 1, key);` `}`   `/* Function to get pivot. For array` `   ``3, 4, 5, 6, 1, 2 it returns 3 (index of 6) */` `int` `findPivot(``int` `arr[], ``int` `low, ``int` `high)` `{` `    ``// base cases` `    ``if` `(high < low)` `        ``return` `-1;` `    ``if` `(high == low)` `        ``return` `low;`   `    ``int` `mid = (low + high) / 2; ``/*low + (high - low)/2;*/` `    ``if` `(mid < high && arr[mid] > arr[mid + 1])` `        ``return` `mid;` `    ``if` `(mid > low && arr[mid] < arr[mid - 1])` `        ``return` `(mid - 1);` `    ``if` `(arr[low] >= arr[mid])` `        ``return` `findPivot(arr, low, mid - 1);` `    ``return` `findPivot(arr, mid + 1, high);` `}`   `/* Standard Binary Search function*/` `int` `binarySearch(``int` `arr[], ``int` `low, ``int` `high, ``int` `key)` `{` `    ``if` `(high < low)` `        ``return` `-1;` `    ``int` `mid = (low + high) / 2; ``/*low + (high - low)/2;*/` `    ``if` `(key == arr[mid])` `        ``return` `mid;` `    ``if` `(key > arr[mid])` `        ``return` `binarySearch(arr, (mid + 1), high, key);` `    ``return` `binarySearch(arr, low, (mid - 1), key);` `}`   `/* Driver program to check above functions */` `int` `main()` `{` `    ``// Let us search 3 in below array` `    ``int` `arr1[] = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };` `    ``int` `n = ``sizeof``(arr1) / ``sizeof``(arr1);` `    ``int` `key = 3;` `    ``printf``(``"Index of the element is : %d"``,` `           ``pivotedBinarySearch(arr1, n, key));` `    ``return` `0;` `}`

## Java

 `/* Java program to search an element` `   ``in a sorted and pivoted array*/`   `class` `Main {`   `    ``/* Searches an element key in a` `       ``pivoted sorted array arrp[]` `       ``of size n */` `    ``static` `int` `pivotedBinarySearch(``int` `arr[], ``int` `n,` `                                   ``int` `key)` `    ``{` `        ``int` `pivot = findPivot(arr, ``0``, n - ``1``);`   `        ``// If we didn't find a pivot, then` `        ``// array is not rotated at all` `        ``if` `(pivot == -``1``)` `            ``return` `binarySearch(arr, ``0``, n - ``1``, key);`   `        ``// 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` `(arr[``0``] <= key)` `            ``return` `binarySearch(arr, ``0``, pivot - ``1``, key);` `        ``return` `binarySearch(arr, pivot + ``1``, n - ``1``, key);` `    ``}`   `    ``/* Function to get pivot. For array` `       ``3, 4, 5, 6, 1, 2 it returns` `       ``3 (index of 6) */` `    ``static` `int` `findPivot(``int` `arr[], ``int` `low, ``int` `high)` `    ``{` `        ``// base cases` `        ``if` `(high < low)` `            ``return` `-``1``;` `        ``if` `(high == low)` `            ``return` `low;`   `        ``/* low + (high - low)/2; */` `        ``int` `mid = (low + high) / ``2``;` `        ``if` `(mid < high && arr[mid] > arr[mid + ``1``])` `            ``return` `mid;` `        ``if` `(mid > low && arr[mid] < arr[mid - ``1``])` `            ``return` `(mid - ``1``);` `        ``if` `(arr[low] >= arr[mid])` `            ``return` `findPivot(arr, low, mid - ``1``);` `        ``return` `findPivot(arr, mid + ``1``, high);` `    ``}`   `    ``/* Standard Binary Search function */` `    ``static` `int` `binarySearch(``int` `arr[], ``int` `low, ``int` `high,` `                            ``int` `key)` `    ``{` `        ``if` `(high < low)` `            ``return` `-``1``;`   `        ``/* low + (high - low)/2; */` `        ``int` `mid = (low + high) / ``2``;` `        ``if` `(key == arr[mid])` `            ``return` `mid;` `        ``if` `(key > arr[mid])` `            ``return` `binarySearch(arr, (mid + ``1``), high, key);` `        ``return` `binarySearch(arr, low, (mid - ``1``), key);` `    ``}`   `    ``// main function` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``// Let us search 3 in below array` `        ``int` `arr1[] = { ``5``, ``6``, ``7``, ``8``, ``9``, ``10``, ``1``, ``2``, ``3` `};` `        ``int` `n = arr1.length;` `        ``int` `key = ``3``;` `        ``System.out.println(` `            ``"Index of the element is : "` `            ``+ pivotedBinarySearch(arr1, n, key));` `    ``}` `}`

## Python3

 `# Python Program to search an element` `# in a sorted and pivoted array`   `# Searches an element key in a pivoted` `# sorted array arrp[] of size n` `def` `pivotedBinarySearch(arr, n, key):`   `    ``pivot ``=` `findPivot(arr, ``0``, n``-``1``)`   `    ``# If we didn't find a pivot,` `    ``# then array is not rotated at all` `    ``if` `pivot ``=``=` `-``1``:` `        ``return` `binarySearch(arr, ``0``, n``-``1``, key)`   `    ``# 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` `arr[``0``] <``=` `key:` `        ``return` `binarySearch(arr, ``0``, pivot``-``1``, key)` `    ``return` `binarySearch(arr, pivot ``+` `1``, n``-``1``, key)`     `# Function to get pivot. For array` `# 3, 4, 5, 6, 1, 2 it returns 3` `# (index of 6)` `def` `findPivot(arr, low, high):`   `    ``# base cases` `    ``if` `high < low:` `        ``return` `-``1` `    ``if` `high ``=``=` `low:` `        ``return` `low`   `    ``# low + (high - low)/2;` `    ``mid ``=` `int``((low ``+` `high)``/``2``)`   `    ``if` `mid < high ``and` `arr[mid] > arr[mid ``+` `1``]:` `        ``return` `mid` `    ``if` `mid > low ``and` `arr[mid] < arr[mid ``-` `1``]:` `        ``return` `(mid``-``1``)` `    ``if` `arr[low] >``=` `arr[mid]:` `        ``return` `findPivot(arr, low, mid``-``1``)` `    ``return` `findPivot(arr, mid ``+` `1``, high)`   `# Standard Binary Search function` `def` `binarySearch(arr, low, high, key):`   `    ``if` `high < low:` `        ``return` `-``1`   `    ``# low + (high - low)/2;` `    ``mid ``=` `int``((low ``+` `high)``/``2``)`   `    ``if` `key ``=``=` `arr[mid]:` `        ``return` `mid` `    ``if` `key > arr[mid]:` `        ``return` `binarySearch(arr, (mid ``+` `1``), high,` `                            ``key)` `    ``return` `binarySearch(arr, low, (mid ``-` `1``), key)`     `# Driver program to check above functions` `# Let us search 3 in below array` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr1 ``=` `[``5``, ``6``, ``7``, ``8``, ``9``, ``10``, ``1``, ``2``, ``3``]` `    ``n ``=` `len``(arr1)` `    ``key ``=` `3` `    ``print``(``"Index of the element is : "``, \` `          ``pivotedBinarySearch(arr1, n, key))`   `# This is contributed by Smitha Dinesh Semwal`

## C#

 `// C# program to search an element` `// in a sorted and pivoted array` `using` `System;`   `class` `main {`   `    ``// Searches an element key in a` `    ``// pivoted sorted array arrp[]` `    ``// of size n` `    ``static` `int` `pivotedBinarySearch(``int``[] arr,` `                                   ``int` `n, ``int` `key)` `    ``{` `        ``int` `pivot = findPivot(arr, 0, n - 1);`   `        ``// If we didn't find a pivot, then` `        ``// array is not rotated at all` `        ``if` `(pivot == -1)` `            ``return` `binarySearch(arr, 0, n - 1, key);`   `        ``// 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` `(arr <= key)` `            ``return` `binarySearch(arr, 0, pivot - 1, key);`   `        ``return` `binarySearch(arr, pivot + 1, n - 1, key);` `    ``}`   `    ``/* Function to get pivot. For array ` `    ``3, 4, 5, 6, 1, 2 it returns` `    ``3 (index of 6) */` `    ``static` `int` `findPivot(``int``[] arr, ``int` `low, ``int` `high)` `    ``{` `        ``// base cases` `        ``if` `(high < low)` `            ``return` `-1;` `        ``if` `(high == low)` `            ``return` `low;`   `        ``/* low + (high - low)/2; */` `        ``int` `mid = (low + high) / 2;`   `        ``if` `(mid < high && arr[mid] > arr[mid + 1])` `            ``return` `mid;`   `        ``if` `(mid > low && arr[mid] < arr[mid - 1])` `            ``return` `(mid - 1);`   `        ``if` `(arr[low] >= arr[mid])` `            ``return` `findPivot(arr, low, mid - 1);`   `        ``return` `findPivot(arr, mid + 1, high);` `    ``}`   `    ``/* Standard Binary Search function */` `    ``static` `int` `binarySearch(``int``[] arr, ``int` `low,` `                            ``int` `high, ``int` `key)` `    ``{` `        ``if` `(high < low)` `            ``return` `-1;`   `        ``/* low + (high - low)/2; */` `        ``int` `mid = (low + high) / 2;`   `        ``if` `(key == arr[mid])` `            ``return` `mid;` `        ``if` `(key > arr[mid])` `            ``return` `binarySearch(arr, (mid + 1), high, key);`   `        ``return` `binarySearch(arr, low, (mid - 1), key);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `Main()` `    ``{` `        ``// Let us search 3 in below array` `        ``int``[] arr1 = { 5, 6, 7, 8, 9, 10, 1, 2, 3 };` `        ``int` `n = arr1.Length;` `        ``int` `key = 3;` `        ``Console.Write(``"Index of the element is : "` `                      ``+ pivotedBinarySearch(arr1, n, key));` `    ``}` `}`   `// This code is contributed by vt_m.`

## PHP

 ` ``\$arr``[``\$mid``])` `        ``return` `binarySearch(``\$arr``, (``\$mid` `+ 1),` `                                ``\$high``, ``\$key``);` `        `  `    ``else` `        ``return` `binarySearch(``\$arr``, ``\$low``,` `                      ``(``\$mid` `-1), ``\$key``);` `}`   `// Function to get pivot. ` `// For array 3, 4, 5, 6, 1, 2` `// it returns 3 (index of 6)` `function` `findPivot(``\$arr``, ``\$low``, ``\$high``)` `{` `    `  `    ``// base cases` `    ``if` `(``\$high` `< ``\$low``) ` `        ``return` `-1;` `    ``if` `(``\$high` `== ``\$low``) ` `        ``return` `\$low``;` `    `  `    ``/*low + (high - low)/2;*/` `    ``\$mid` `= (``\$low` `+ ``\$high``)/2; ` `    ``if` `(``\$mid` `< ``\$high` `and` `\$arr``[``\$mid``] > ` `                     ``\$arr``[``\$mid` `+ 1])` `        ``return` `\$mid``;` `        `  `    ``if` `(``\$mid` `> ``\$low` `and` `\$arr``[``\$mid``] < ` `                    ``\$arr``[``\$mid` `- 1])` `        ``return` `(``\$mid` `- 1);` `        `  `    ``if` `(``\$arr``[``\$low``] >= ``\$arr``[``\$mid``])` `        ``return` `findPivot(``\$arr``, ``\$low``,` `                          ``\$mid` `- 1);` `        `  `    ``return` `findPivot(``\$arr``, ``\$mid` `+ 1, ``\$high``);` `}`   `// Searches an element key` `// in a pivoted sorted array` `// arr[] of size n */` `function` `pivotedBinarySearch(``\$arr``, ``\$n``, ``\$key``)` `{` `    ``\$pivot` `= findPivot(``\$arr``, 0, ``\$n` `- 1);` `    `  `    ``// If we didn't find a pivot, ` `    ``// then array is not rotated` `    ``// at all` `    ``if` `(``\$pivot` `== -1)` `        ``return` `binarySearch(``\$arr``, 0, ` `                       ``\$n` `- 1, ``\$key``);` `    `  `    ``// 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` `(``\$arr`` <= ``\$key``)` `        ``return` `binarySearch(``\$arr``, 0, ` `                   ``\$pivot` `- 1, ``\$key``);` `        `  `        ``return` `binarySearch(``\$arr``, ``\$pivot` `+ 1, ` `                                ``\$n` `- 1, ``\$key``);` `}`   `// Driver Code` `// Let us search 3 ` `// in below array` `\$arr1` `= ``array``(5, 6, 7, 8, 9, 10, 1, 2, 3);` `\$n` `= ``count``(``\$arr1``);` `\$key` `= 3;`   `// Function calling` `echo` `"Index of the element is : "``, ` `      ``pivotedBinarySearch(``\$arr1``, ``\$n``, ``\$key``);` `            `  `// This code is contributed by anuj_67.` `?>`

## Javascript

 ``

Output

`Index of the element is : 8`

Time Complexity: O(log N) Binary Search requires log n comparisons to find the element.
Space Complexity: O(1)

Thanks to Ajay Mishra for the providing the above solution.

Approach 2 (Direct Binary search on Array without finding Pivot):

The idea is to instead of two or more passes of binary search, the result can be found in one pass of binary search.

The idea is to create a recursive function to implement the binary search where the search region is [l, r]. For each recursive call:

• We calculate the mid value as mid = (l + h) / 2
• Then try to figure out if l to mid is sorted, or (mid+1) to h is sorted
• Based on that decide the next search region and keep on doing this till the element is found or l overcomes h.

Follow the steps mentioned below to implement the idea:

• Use a recursive function to implement binary search to find the key:
• Find middle-point mid = (l + h)/2
• If the key is present at the middle point, return mid.
• Else if the value at l is less than the one at mid then arr[l . . . mid] is sorted
• If the key to be searched lies in the range from arr[l] to arr[mid], recur for arr[l . . . mid].
• Else recur for arr[mid+1 . . . h]
• Else arr[mid+1. . . h] is sorted:
• If the key to be searched lies in the range from arr[mid+1] to arr[h], recur for arr[mid+1. . . h].
• Else recur for arr[l. . . mid]

Follow the below illustration for a better understanding:

Illustration:

Input arr[] = {3, 4, 5, 1, 2}, key = 1
Initially low = 0, high = 4.

low = 0, high = 4:
=> mid = 2
=> arr[mid] = 5, which is not the desired value.
=> arr[low] < arr[mid] So, the left half is sorted.
=> key < arr[low], So the next search region is 3 to 4.

low = 3, high = 4:
=> mid = 3
=> arr[mid] = 1 = key
=> So the element is found at index 3.

The element is found at index 3.

Below is the implementation of the above idea:

## C++

 `// Search an element in sorted and rotated` `// array using single pass of Binary Search` `#include ` `using` `namespace` `std;`   `// Returns index of key in arr[l..h] if` `// key is present, otherwise returns -1` `int` `search(``int` `arr[], ``int` `l, ``int` `h, ``int` `key)` `{` `    ``if` `(l > h)` `        ``return` `-1;`   `    ``int` `mid = (l + h) / 2;` `    ``if` `(arr[mid] == key)` `        ``return` `mid;`   `    ``/* If arr[l...mid] is sorted */` `    ``if` `(arr[l] <= arr[mid]) {` `        ``/* As this subarray is sorted, we can quickly` `        ``check if key lies in half or other half */` `        ``if` `(key >= arr[l] && key <= arr[mid])` `            ``return` `search(arr, l, mid - 1, key);` `        ``/*If key not lies in first half subarray,` `           ``Divide other half  into two subarrays,` `           ``such that we can quickly check if key lies` `           ``in other half */` `        ``return` `search(arr, mid + 1, h, key);` `    ``}`   `    ``/* If arr[l..mid] first subarray is not sorted, then` `    ``arr[mid... h] must be sorted subarray */` `    ``if` `(key >= arr[mid] && key <= arr[h])` `        ``return` `search(arr, mid + 1, h, key);`   `    ``return` `search(arr, l, mid - 1, key);` `}`   `// Driver program` `int` `main()` `{` `    ``int` `arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `key = 3;` `    ``int` `i = search(arr, 0, n - 1, key);`   `    ``if` `(i != -1)` `        ``cout << ``"Index: "` `<< i << endl;` `    ``else` `        ``cout << ``"Key not found"``;` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## C

 `// Search an element in sorted and rotated` `// array using single pass of Binary Search` `#include `   `// Returns index of key in arr[l..h] if` `// key is present, otherwise returns -1` `int` `search(``int` `arr[], ``int` `l, ``int` `h, ``int` `key)` `{` `    ``if` `(l > h)` `        ``return` `-1;`   `    ``int` `mid = (l + h) / 2;` `    ``if` `(arr[mid] == key)` `        ``return` `mid;`   `    ``/* If arr[l...mid] is sorted */` `    ``if` `(arr[l] <= arr[mid]) {` `        ``/* As this subarray is sorted, we can quickly` `        ``check if key lies in half or other half */` `        ``if` `(key >= arr[l] && key <= arr[mid])` `            ``return` `search(arr, l, mid - 1, key);` `        ``/*If key not lies in first half subarray,` `           ``Divide other half  into two subarrays,` `           ``such that we can quickly check if key lies` `           ``in other half */` `        ``return` `search(arr, mid + 1, h, key);` `    ``}`   `    ``/* If arr[l..mid] first subarray is not sorted, then` `    ``arr[mid... h] must be sorted subarray */` `    ``if` `(key >= arr[mid] && key <= arr[h])` `        ``return` `search(arr, mid + 1, h, key);`   `    ``return` `search(arr, l, mid - 1, key);` `}`   `// Driver program` `int` `main()` `{` `    ``int` `arr[] = { 4, 5, 6, 7, 8, 9, 1, 2, 3 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);` `    ``int` `key = 3;` `    ``int` `i = search(arr, 0, n - 1, key);`   `    ``if` `(i != -1)` `        ``printf``(``"Index: %d\n"``, i);` `    ``else` `        ``printf``(``"Key not found"``);` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Java

 `/* Java program to search an element in` `   ``sorted and rotated array using` `   ``single pass of Binary Search*/`   `class` `Main {` `    ``// Returns index of key in arr[l..h]` `    ``// if key is present, otherwise returns -1` `    ``static` `int` `search(``int` `arr[], ``int` `l, ``int` `h, ``int` `key)` `    ``{` `        ``if` `(l > h)` `            ``return` `-``1``;`   `        ``int` `mid = (l + h) / ``2``;` `        ``if` `(arr[mid] == key)` `            ``return` `mid;`   `        ``/* If arr[l...mid] first subarray is sorted */` `        ``if` `(arr[l] <= arr[mid]) {` `            ``/* As this subarray is sorted, we` `               ``can quickly check if key lies in` `               ``half or other half */` `            ``if` `(key >= arr[l] && key <= arr[mid])` `                ``return` `search(arr, l, mid - ``1``, key);` `            ``/*If key not lies in first half subarray,` `           ``Divide other half  into two subarrays,` `           ``such that we can quickly check if key lies` `           ``in other half */` `            ``return` `search(arr, mid + ``1``, h, key);` `        ``}`   `        ``/* If arr[l..mid] first subarray is not sorted,` `           ``then arr[mid... h] must be sorted subarray*/` `        ``if` `(key >= arr[mid] && key <= arr[h])` `            ``return` `search(arr, mid + ``1``, h, key);`   `        ``return` `search(arr, l, mid - ``1``, key);` `    ``}`   `    ``// main function` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `arr[] = { ``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``1``, ``2``, ``3` `};` `        ``int` `n = arr.length;` `        ``int` `key = ``3``;` `        ``int` `i = search(arr, ``0``, n - ``1``, key);` `        ``if` `(i != -``1``)` `            ``System.out.println(``"Index: "` `+ i);` `        ``else` `            ``System.out.println(``"Key not found"``);` `    ``}` `}`   `// This code is contributed by Aditya Kumar (adityakumar129)`

## Python3

 `# Search an element in sorted and rotated array using` `# single pass of Binary Search`   `# Returns index of key in arr[l..h] if key is present,` `# otherwise returns -1` `def` `search(arr, l, h, key):` `    ``if` `l > h:` `        ``return` `-``1`   `    ``mid ``=` `(l ``+` `h) ``/``/` `2` `    ``if` `arr[mid] ``=``=` `key:` `        ``return` `mid`   `    ``# If arr[l...mid] is sorted` `    ``if` `arr[l] <``=` `arr[mid]:`   `        ``# As this subarray is sorted, we can quickly` `        ``# check if key lies in half or other half` `        ``if` `key >``=` `arr[l] ``and` `key <``=` `arr[mid]:` `            ``return` `search(arr, l, mid``-``1``, key)` `        ``return` `search(arr, mid ``+` `1``, h, key)`   `    ``# If arr[l..mid] is not sorted, then arr[mid... r]` `    ``# must be sorted` `    ``if` `key >``=` `arr[mid] ``and` `key <``=` `arr[h]:` `        ``return` `search(arr, mid ``+` `1``, h, key)` `    ``return` `search(arr, l, mid``-``1``, key)`     `# Driver program` `if` `__name__ ``=``=` `'__main__'``:` `    ``arr ``=` `[``4``, ``5``, ``6``, ``7``, ``8``, ``9``, ``1``, ``2``, ``3``]` `    ``key ``=` `3` `    ``i ``=` `search(arr, ``0``, ``len``(arr)``-``1``, key)` `    ``if` `i !``=` `-``1``:` `        ``print``(``"Index: % d"` `%` `i)` `    ``else``:` `        ``print``(``"Key not found"``)`   `# This code is contributed by Shreyanshi Arun`

## C#

 `/* C# program to search an element in` `sorted and rotated array using` `single pass of Binary Search*/` `using` `System;`   `class` `GFG {`   `    ``// Returns index of key in arr[l..h]` `    ``// if key is present, otherwise` `    ``// returns -1` `    ``static` `int` `search(``int``[] arr, ``int` `l, ``int` `h, ``int` `key)` `    ``{` `        ``if` `(l > h)` `            ``return` `-1;`   `        ``int` `mid = (l + h) / 2;`   `        ``if` `(arr[mid] == key)` `            ``return` `mid;`   `        ``/* If arr[l...mid] is sorted */` `        ``if` `(arr[l] <= arr[mid]) {`   `            ``/* As this subarray is sorted, we` `            ``can quickly check if key lies in` `            ``half or other half */` `            ``if` `(key >= arr[l] && key <= arr[mid])` `                ``return` `search(arr, l, mid - 1, key);`   `            ``return` `search(arr, mid + 1, h, key);` `        ``}`   `        ``/* If arr[l..mid] is not sorted,` `        ``then arr[mid... r] must be sorted*/` `        ``if` `(key >= arr[mid] && key <= arr[h])` `            ``return` `search(arr, mid + 1, h, key);`   `        ``return` `search(arr, l, mid - 1, key);` `    ``}`   `    ``// main function` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { 4, 5, 6, 7, 8, 9, 1, 2, 3 };` `        ``int` `n = arr.Length;` `        ``int` `key = 3;` `        ``int` `i = search(arr, 0, n - 1, key);`   `        ``if` `(i != -1)` `            ``Console.WriteLine(``"Index: "` `+ i);` `        ``else` `            ``Console.WriteLine(``"Key not found"``);` `    ``}` `}`   `// This code is contributed by anuj_67.`

## PHP

 ` ``\$h``) ``return` `-1;`   `    ``\$mid` `= ``floor``((``\$l` `+ ``\$h``) / 2);` `    ``if` `(``\$arr``[``\$mid``] == ``\$key``)` `        ``return` `\$mid``;`   `    ``/* If arr[l...mid] is sorted */` `    ``if` `(``\$arr``[``\$l``] <= ``\$arr``[``\$mid``])` `    ``{` `        `  `        ``/* As this subarray is ` `           ``sorted, we can quickly` `           ``check if key lies in ` `           ``half or other half */` `        ``if` `(``\$key` `>= ``\$arr``[``\$l``] ``and` `            ``\$key` `<= ``\$arr``[``\$mid``])` `                ``return` `search(``\$arr``, ``\$l``, ` `                       ``\$mid` `- 1, ``\$key``);`   `        ``return` `search(``\$arr``, ``\$mid` `+ 1,` `                           ``\$h``, ``\$key``);` `    ``}`   `    ``/* If arr[l..mid] is not ` `       ``sorted, then arr[mid... r]` `       ``must be sorted*/` `    ``if` `(``\$key` `>= ``\$arr``[``\$mid``] ``and` `          ``\$key` `<= ``\$arr``[``\$h``])` `        ``return` `search(``\$arr``, ``\$mid` `+ 1, ` `                            ``\$h``, ``\$key``);`   `    ``return` `search(``\$arr``, ``\$l``, ` `             ``\$mid``-1, ``\$key``);` `}`   `    ``// Driver Code` `    ``\$arr` `= ``array``( 5, 6, 7, 8, 9, 10, 1, 2, 3 );` `    ``\$n` `= sizeof(``\$arr``);` `    ``\$key` `= 3;` `    ``\$i` `= search(``\$arr``, 0, ``\$n``-1, ``\$key``);`   `    ``if` `(``\$i` `!= -1)` `        ``echo` `"Index: "``, ``\$i``, ``" \n"``;` `    ``else` `        ``echo` `"Key not found"``;`   `// This code is contributed by ajit` `?>`

## Javascript

 ``

Output

`Index: 8`

Time Complexity: O(log N). Binary Search requires log n comparisons to find the element. So time complexity is O(log n).
Space Complexity: O(1). As no extra space is required.

Thanks to Gaurav Ahirwar for suggesting the above solution.

How to handle duplicates?
At first look, it doesn’t look possible to search in O(Log N) time in all cases when duplicates are allowed.
For example consider searching 0 in {2, 2, 2, 2, 2, 2, 2, 2, 0, 2} and {2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}.
Look into the following article to find a solution to this issue: https://www.geeksforgeeks.org/search-an-element-in-a-sorted-and-rotated-array-with-duplicates/

Similar Articles:

Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem.

My Personal Notes arrow_drop_up
Recommended Articles
Page :