forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPivotedBinarySearch.java
68 lines (59 loc) · 1.87 KB
/
PivotedBinarySearch.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package me.ramswaroop.arrays;
import me.ramswaroop.arrays.searching.BinarySearch;
/**
* Created by IntelliJ IDEA.
*
* @author: ramswaroop
* @date: 5/31/15
* @time: 10:44 PM
*/
public class PivotedBinarySearch {
/**
* Search an element in a sorted pivoted array {@param a}.
* <p/>
* Example,
* 1) For array [3,4,5,1,2] pivot is 5
* 2) For array [6,7,8,5,4] pivot is 8
*
* @param a
* @param n
* @return
*/
public static int pivotedBinarySearch(int a[], int n) {
int pivot = findPivot(a, 0, a.length - 1);
if (pivot == -1 || a[pivot] == n) {
return pivot;
} else if (n <= a[0]) {
return BinarySearch.binarySearch(a, n, pivot + 1, a.length - 1);
} else {
return BinarySearch.binarySearch(a, n, 0, pivot - 1);
}
}
/**
* Finds the pivot element in array {@param a}. Pivot element is the only
* element for which next element to it is smaller than it.
*
* @param a
* @param low
* @param high
* @return
*/
public static int findPivot(int a[], int low, int high) {
if (low > high) return -1;
if (low == high) return low;
int mid = (low + high) / 2;
if (a[mid] > a[mid + 1] && a[mid] > a[mid - 1]) {
return mid;
} else if (a[mid] > a[mid - 1] && a[mid] < a[mid + 1]) {
return findPivot(a, mid + 1, a.length - 1);
} else {
return findPivot(a, 0, mid - 1);
}
}
public static void main(String a[]) {
System.out.println("Pivot: " + findPivot(new int[]{1, 2, 3, 4, 5}, 0, 3));
System.out.println("Index: " + pivotedBinarySearch(new int[]{1, 2, 3, 4, 5}, 4));
System.out.println("Pivot: " + findPivot(new int[]{5}, 0, 0));
System.out.println("Index: " + pivotedBinarySearch(new int[]{5}, 5));
}
}