3. Search in Rotated sorted array
3. Search in Rotated sorted array
Problem link :- click here
package program;
public class Searching__3
{
/*
Search in a rotated sorted array
arr[] = {4, 5, 6, 7, 0, 1, 2, 3} key = 0
output : 4
lets split the array into two parts
we have to find pivot for that
pivot means the element which is greater than its left and right element
we will find that element using binary search
and see which array does the key belongs to and call
binary search to that array
*/
static int findPivot(int arr[], int low, int high)
{
if(low > high)
return -1;
if(high == low)
return high;
int mid = (low + high)/2;
if( arr[mid-1] < arr[mid] && arr[mid] > arr[mid+1] )
return mid;
else if( arr[mid] < arr[mid-1] )
return findPivot(arr, low, mid-1);
else if( arr[mid] < arr[mid+1] )
return findPivot(arr, mid+1, high);
return -1;
}
static int binarySearch(int arr[], int low, int high, int key)
{
int mid = (low+high)/2;
if(arr[mid] == key)
return mid;
else if( key < arr[mid] )
return binarySearch(arr, low, mid-1, key);
else
return binarySearch(arr, mid+1, high, key);
}
static int sortedRotatedSearch(int arr[], int n, int key)
{
int pivot = findPivot(arr, 0, n-1);
if( key == arr[pivot] )
return pivot;
else if( key > arr[0] )
return binarySearch(arr, 0, pivot, key);
else
return binarySearch(arr, pivot+1, n-1, key);
}
public static void main(String[] args)
{
int arr[] = {4, 5, 6, 7, 0, 1, 2, 3};
int key = 6;
int ans = sortedRotatedSearch(arr, arr.length, key);
if(ans == -1)
System.out.println("Not found");
else
System.out.println("Found at " + ans);
}
}
Time complexity :- O()
Space complexity :- O()
Comments
Post a Comment