-
Notifications
You must be signed in to change notification settings - Fork 93
/
FindPivotInSortedRotatedArray
94 lines (79 loc) · 2.29 KB
/
FindPivotInSortedRotatedArray
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package array;
/**
* <b>IDeserve <br>
* <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/
* IDeserve</a> <br>
* <br>
* Find Pivot in Sorted Rotated Array</b><br>
* Given a sorted integer array which is rotated any number of times, find the
* pivot index i.e. index of the minimum element of the array.
*
* Example: In array {78, 82, 99, 10, 23, 35, 49, 51, 60}<br/>
* Pivot index is 3
*
* <br>
* <br>
* <a href="https://www.youtube.com/watch?v=ggLGjf_XiNQ">Find Pivot in Sorted
* Rotated Array Youtube Link</a>
*
* @author Saurabh
*
*/
public class FindPivotInSortedRotatedArray {
// O(n) solution - Linear Search
public static int findPivotLinear(int[] array) {
int pivot = -1;
if (array != null && array.length > 0) {
pivot = 0;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
pivot = i + 1;
break;
}
}
}
return pivot;
}
// O(log n) solution - Binary Search
public static int findPivotBinarySearch(int[] array) {
if (array == null || array.length == 0) {
return -1;
}
// Case when array is not rotated. Then first index is the pivot
if (array.length == 1 || array[0] < array[array.length - 1]) {
return 0;
}
int start = 0, end = array.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
// check if mid+1 is pivot
if (mid < array.length-1 && array[mid] > array[mid+1]) {
return (mid + 1);
} else if (array[start] <= array[mid]) {
// If array[start] <= array[mid],
// it means from start to mid, all elements are in sorted order,
// so pivot will be in second half
start = mid + 1;
} else {
// else pivot lies in first half, so we find the pivot in first half
end = mid - 1;
}
}
return 0;
}
public static void main(String[] args) {
int array[] = { 5, 4 };
findPivotLinearTest(array);
findPivotBinarySearchTest(array);
}
public static void findPivotLinearTest(int array[]) {
int index = findPivotLinear(array);
System.out.println("Pivot "
+ (index >= 0 ? (" found at index " + index) : " not found!"));
}
public static void findPivotBinarySearchTest(int array[]) {
int index = findPivotBinarySearch(array);
System.out.println("Pivot "
+ (index >= 0 ? (" found at index " + index) : " not found!"));
}
}