Java Program for Search an element in a sorted and rotated array
Last Updated :
19 Sep, 2023
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.
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.
Basic Solution:
Approach:
- The idea is to find the pivot point, divide the array in two sub-arrays and perform binary search.
- 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.
- Using the above statement and binary search pivot can be found.
- After the pivot is found out divide the array in two sub-arrays.
- 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:
Java
class Main {
static int pivotedBinarySearch( int arr[], int n, int key)
{
int pivot = findPivot(arr, 0 , n - 1 );
if (pivot == - 1 )
return binarySearch(arr, 0 , n - 1 , key);
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);
}
static int findPivot( int arr[], int low, int high)
{
if (high < low)
return - 1 ;
if (high == low)
return low;
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);
}
static 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);
}
public static void main(String args[])
{
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));
}
}
|
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.
Thanks to Ajay Mishra for initial solution.
Improved Solution:
Approach: Instead of two or more pass of binary search the result can be found in one pass of binary search. The binary search needs to be modified to perform the search. The idea is to create a recursive function that takes l and r as range in input and the key.
1) Find middle point mid = (l + h)/2
2) If key is present at middle point, return mid.
3) Else If arr[l..mid] is sorted
a) If key to be searched lies in range from arr[l]
to arr[mid], recur for arr[l..mid].
b) Else recur for arr[mid+1..h]
4) Else (arr[mid+1..h] must be sorted)
a) If key to be searched lies in range from arr[mid+1]
to arr[h], recur for arr[mid+1..h].
b) Else recur for arr[l..mid]
Below is the implementation of above idea:
Java
class Main {
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] <= arr[mid]) {
if (key >= arr[l] && key <= arr[mid])
return search(arr, l, mid - 1 , key);
return search(arr, mid + 1 , h, key);
}
if (key >= arr[mid] && key <= arr[h])
return search(arr, mid + 1 , h, key);
return search(arr, l, mid - 1 , key);
}
public static void main(String args[])
{
int arr[] = { 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 };
int n = arr.length;
int key = 6 ;
int i = search(arr, 0 , n - 1 , key);
if (i != - 1 )
System.out.println( "Index: " + i);
else
System.out.println( "Key not found" );
}
}
|
Output:
Index: 2
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).
As no extra space is required.
Approach 3: Using Stacks:
The stack-based approach can be used to search for an element in a sorted and rotated array. The basic idea is to traverse the array and push the elements onto a stack until the element being searched is found. Once the element is found, the index of the element is returned.
To implement this approach, we can start by creating an empty stack and pushing the first element
of the array onto the stack. Then, we can traverse the remaining elements of the array and compare
them with the element being searched. If the element being searched is found, we return the index
of the element. Otherwise, we push the element onto the stack.
If the current element is less than the top element of the stack, it means that we have
reached the end of the sorted part of the array. So, we pop the elements from the stack until
we find an element that is smaller than the current element or the stack becomes empty.
If the stack becomes empty, it means that we have traversed the entire array and the element
is not present.
If the current element is greater than the top element of the stack, it means that we are still
in the sorted part of the array. So, we simply push the element onto the stack and continue
traversing the array.
Here is the code of above approach:
Java
import java.util.Stack;
class Main {
public static int search( int [] arr, int n, int key) {
Stack<Integer> s = new Stack<Integer>();
for ( int i = 0 ; i < n; i++)
s.push(arr[i]);
int pivot = 0 ;
while (!s.empty()) {
int top = s.pop();
if (s.empty() || top < s.peek()) {
pivot = n - pivot - 1 ;
break ;
}
pivot++;
}
int l = 0 , h = n - 1 ;
if (key >= arr[pivot] && key <= arr[h])
l = pivot;
else
h = pivot - 1 ;
while (l <= h) {
int mid = (l + h) / 2 ;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
l = mid + 1 ;
else
h = mid - 1 ;
}
return - 1 ;
}
public static void main(String[] args) {
int [] arr = { 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 };
int n = arr.length;
int key = 6 ;
int i = search(arr, n, key);
if (i != - 1 )
System.out.println( "Index: " + i);
else
System.out.println( "Key not found" );
}
}
|
Output:
Index: 2
Complexity Analysis:
Time Complexity: O(N), where N is the size of the array
Space Complexity: O(N), where N is the size of the array
Thanks to Gaurav Ahirwar for suggesting above solution.
How to handle duplicates?
It doesn’t look possible to search in O(Logn) 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}.
It doesn’t look possible to decide whether to recur for the left half or right half by doing a constant number of comparisons at the middle.
Similar Articles:
Please write comments if you find any bug in the above codes/algorithms, or find other ways to solve the same problem.
Please refer complete article on Search an element in a sorted and rotated array for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...