Tuesday, 16 May 2017

1. Search element in rotated sorted array




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;

}
}

No comments:

Post a Comment

3. Java Program to create Binary Tree