Java program to search an element in a sorted rotated array.
Given an array which is sorted but rotated. Now our task is to search an element in the array. [3,4,5,1,2]
Since searching a sorted array is faster than unsorted one. We will try to bring this rotated array to initial position and then peform the search.
After we search in the sorted array, we convert the index of sorted array to rotated array.
import java.util.Arrays;
public class RotatedArray{
public static void main(String[] args) {
int[] arr = new int[]{3,4,5,1,2};
int pivot = -1;
for(int i=0;i<arr.length-1;i++){
if(arr[i]>arr[i+1]){
pivot = i+1;
}
}
//Fill up the sorted array
int[] sorted = new int[arr.length];
int index = 0;
//from pivot to end
for(int i=pivot; i<arr.length;i++)
sorted[index++] = arr[i];
//from start to pivot
for(int i=0; i<pivot;i++)
sorted[index++] = arr[i];
System.out.println(Arrays.toString(arr));
// System.out.println(Arrays.toString(sorted));
int pos = Arrays.binarySearch(sorted, Integer.parseInt(args[0]));
System.out.println("index: " + ( pos + pivot ) % arr.length );
}
}
The above program takes the element as input and gives out the index of the element.
java RotatedArray 3
index: 0