-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountRotationsInArray.java
More file actions
39 lines (38 loc) · 978 Bytes
/
countRotationsInArray.java
File metadata and controls
39 lines (38 loc) · 978 Bytes
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
public class countRotationsInArray {
// https://www.geeksforgeeks.org/find-rotation-count-rotated-sorted-array/
public static void main(String[] args) {
int[] arr = {4, 5, 6, 7, 8, 0, 1, 2};
System.out.println(countRotations(arr));
}
static int countRotations(int[] arr)
{
int pivot = peak(arr);
return pivot+1;
}
static int peak(int[] arr)
{
int start = 0;
int end = arr.length-1;
while(start <= end)
{
int mid = start + (end - start)/2;
if(mid < end && arr[mid] > arr[mid+1])
{
return mid;
}
if(start < mid && arr[mid] < arr[mid-1])
{
return mid-1;
}
if(arr[mid] <= arr[start])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
return -1;
}
}