Skip to content

Instantly share code, notes, and snippets.

@psvnlsaikumar
Created January 11, 2020 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psvnlsaikumar/445d0639e2e3a55dc8f7b62a720d3c4c to your computer and use it in GitHub Desktop.
Save psvnlsaikumar/445d0639e2e3a55dc8f7b62a720d3c4c to your computer and use it in GitHub Desktop.
Binary search implementation over a rotated array
public static int search(final int[] A, int B) {
int index = -1;
int pivot = pivotSearch(A);
int low = pivot;
int high = pivot - 1;
int pivotRightBoundary = A[A.length - 1];
int pivotLeftBoundary = A[0];
// System.out.println("Pivot is : " + pivot + "\nPivot Element is :" + A[pivot] + "\nPivorRightBoundary : " + pivotRightBoundary + "\npivotLeftBoundary :" + pivotLeftBoundary);
if(pivot == -1) return binarySearch(A, B);
if(A[pivot] == B) return pivot;
if(A[pivot] < B && B < pivotRightBoundary){
// System.out.println("\nTraversing Right");
int size = pivot - A.length;
if(size < 0) size *= -1;
// System.out.println(size);
int arr[] = new int[size];
for(int i = 0; i < size; i++) arr[i] = A[pivot + i];
int result = binarySearch(arr, B);
if(result == -1) return -1;
else return result + pivot;
}
if(A[pivot] < B && B > pivotRightBoundary){
// System.out.println("\nTraversing left");
int arr[] = new int[pivot];
for(int i = 0; i < pivot; i++) arr[i] = A[i];
return binarySearch(arr, B);
}
return index;
}
public static int binarySearch(final int[] A, int B){
int low = 0;
int high = A.length - 1;
int mid = low + (high - low)/2;
while(low <= high){
if(A[mid] == B) return mid;
if(A[mid] < B){
low = mid + 1;
mid = low + (high - low) /2;
} else if (A[mid] > B && mid != 0){
high = mid - 1;
mid = low + (high - low) /2;
}
// Scanner scan = new Scanner(System.in);
// System.out.println("\nLow is : " + low + "\nHigh is : " + high + "\nMid is " + mid);
// scan.nextInt();
}
return -1;
}
public static int pivotSearch(final int[] A){
int low = 0;
int high = A.length - 1;
int mid = low + (high - low)/2;
// Scanner scan = new Scanner(System.in);
while(low <= high){
// System.out.println("\nLow is : " + low + "\nHigh is : " + high + "\nMid is " + mid + "\nMid Element is :" + A[mid] + "\nHighElement is :" + A[high] + "\nLow element is :" + A[low]);
// scan.nextInt();
if(low == high || low == mid) return -1;
if(A[mid] < A[mid + 1] && A[mid] < A[mid - 1]) return mid;
if(A[mid + 1] < A[mid] && A[mid] > A[mid - 1]) return mid + 1;
if((A[mid] < A[mid + 1] && A[mid] > A[mid - 1]) && A[mid] >= A[high]){
mid += 1;
low = mid;
mid = low + (high - low)/2;
// System.out.println("\nTraversing right");
}
else if(mid!= 0 &&(A[mid] < A[mid + 1] && A[mid] > A[mid - 1]) && (A[mid] <= A[high]) ){
mid -= 1;
high = mid;
mid = low + (high - low)/2;
// System.out.println("\nTraversing left");
}
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment