public class BinarySearch {
public static void main(String[] args) {
int array[] = { 10, 20, 30 };
int ele = 30;
int index = pivotBinarySearch(array, ele, 0, array.length - 1);
System.out.println("index is " + index);
}
public static int pivotBinarySearch(int array[], int ele, int min, int max) {
int pivot = findPivot(array, 0, array.length - 1);
if (pivot == -1 || array[pivot] == ele)
return pivot;
if (array[min] > ele)
return binarySearch(array, ele, pivot + 1, max);
return binarySearch(array, ele, min, pivot - 1);
}
public static int binarySearch(int array[], int ele, int min, int max) {
int middle = (min + max) / 2;
if (ele == array[middle])
return middle;
if (min == max)
return -1;
if (ele < array[middle])
return binarySearch(array, ele, min, middle - 1);
return binarySearch(array, ele, middle + 1, max);
}
public static int findPivot(int array[], int min, int max) {
System.out.println(min + " " + max);
int middle = (min + max) / 2;
if (max - min == 1 && array[min] > array[max])
return min;
if (array[middle] > array[max])
return findPivot(array, middle, max);
if (array[min] > array[middle])
return findPivot(array, min, middle);
return -1;
}
}
|
Tuesday, 16 May 2017
1. Search element in rotated sorted array
Subscribe to:
Post Comments (Atom)
-
1. Producer consumer problem. In computing, the producer–consumer problem (also known as the bounded-buffer problem) is a classic examp...
-
1. What is race condition? If multiple threads are operating simultaneously on same java object then there may be a chance of data cons...
-
1. Is that give any effect if we call notify() or notifyAll() before calling of wait() No, before wait() if we call notify() or notify...
No comments:
Post a Comment