C++ program to search an element in a sorted rotated array

C++ProgrammingServer Side Programming

We are given a sorted array which is rotated about a point. We are also given a key to search in the array. The logic adopted to search for an element in this rotated array is −

  • First, we find the middle element of the array. If the key is present, then we return that the key is present in the array.

  • If the key is not present in the middle, we can see if the left part of the array(left to mid) is sorted or not. If sorted, we can search for the key in the left part otherwise, we can go for the search on the right part(mid+1, right)

  • If the key is not found in the middle and the left part is not sorted, then we would sort the right part and we can see if the key is present on the right part, or we will search on the left side of the array

  • Else we return not found.

Let’s see some input-ouput scenarios below −

Imagine there is an array consisting elements in it. Example, 2 ,5, 7, 9, 11 and after rotating it became 5, 9, 11, 2, 7. Let’s assume key of the array is 2.

Input: arr[] = {5, 9, 11, 2, 7}, Key=2
Output: Element "2" found at 3rd index

Let’s assume another scenario where the key is not in the specified array.

Input: arr[] = {10, 23, 45, 77, 84}, Key=90
Output: Element "90" not found.


The below following steps are the way of approach.

  • Find middle element of the array.

  • Divide the array into two parts. ( mid = left + right ) / 2

  • Check whether key is middle element or not.

  • Else if , check element in the left part of array and it is sorted

  • Else if, check element in right part (mid+1, right)

  • Else if, sort left part and check

  • Else, return element not found.


For example, assume we have an array “2,3,4,5,6,7,8” and the rotated array is “5, 6, 7, 8, 2, 3, 4”. The key of this array is 2.

The C++ implementation of this operation is as follows −

#include <iostream> #include <vector> using namespace std; bool solve(vector<int> arr, int left, int right, int key) { if (left > right) { return false; } int mid = (left + right)/2; if (arr[mid] == key) { return true; } if (arr[left] <= arr[mid]) { if (key >= arr[left] && key <= arr[mid]) { return solve(arr, left, mid-1, key); } return solve(arr, mid+1, right, key); } if (key >= arr[mid] && key <= arr[right]) return solve(arr, mid+1, right, key); return solve(arr, left, mid-1, key); } int main() { vector<int> arr = {5, 6, 7, 8, 2, 3, 4}; int key = 2; if(solve(arr, 0, arr.size()-1, key)) cout << key << " is present"; else cout << key << " is not present"; return 0; }


2 is present


Another approach for solving this problem would be to find out the pivot point or the index where the array is rotated about and then do a binary search for the side. Our approach takes only 1 binary search to solve the problem. Whenever we see search and sorted array we should search for binary search as one of the methods.

Updated on 10-Aug-2022 09:58:08