VOOZH about

URL: https://www.geeksforgeeks.org/c/c-program-for-search-an-element-in-a-sorted-and-rotated-array/

⇱ C Program for Search an element in a sorted and rotated array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program for Search an element in a sorted and rotated array

Last Updated : 23 Jul, 2025

An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.
 

👁 sortedPivotedArray


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
Output : Not found

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


 


 


All solutions provided here assume that all elements in the array are distinct.
 
Approach: 
 

  1. The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.
  2. The main idea for finding pivot is - for a sorted (in increasing order) and pivoted array, pivot element is the only element for which next element to it is smaller than it.
  3. Using the above statement and binary search pivot can be found.
  4. After the pivot is found out divide the array in two sub-arrays.
  5. Now the individual sub - arrays are sorted so the element can be searched using Binary Search.


Implementation: 
 

Input arr[] = {3, 4, 5, 1, 2}
Element to Search = 1
 1) Find out pivot point and divide the array in two
 sub-arrays. (pivot = 2) /*Index of 5*/
 2) Now call binary search for one of the two sub-arrays.
 (a) If element is greater than 0th element then
 search in left array
 (b) Else Search in right array
 (1 will go in else as 1 < 0th element(3))
 3) If element is found in selected sub-array then return index
 Else return -1.


Below is the implementation of the above approach: 
 

Output: 
 

Index of the element is : 8


Complexity Analysis: 
 

  • 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), No extra space is required.
Please refer complete article on Search an element in a sorted and rotated array for more details!
Comment