-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountRotationsInSortedArray
More file actions
41 lines (34 loc) · 1.02 KB
/
CountRotationsInSortedArray
File metadata and controls
41 lines (34 loc) · 1.02 KB
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
public class CountRotations{
static int countRotations(int arr[], int low, int high)
{
// This condition is needed to handle the case
// when array is not rotated at all
if (high < low)
return 0;
// If there is only one element left
if (high == low)
return low;
// Find mid
int mid = low + (high - low)/2; /*(low + high)/2;*/
// Check if element (mid+1) is minimum element.
// Consider the cases like {3, 4, 5, 1, 2}
if (mid < high && arr[mid+1] < arr[mid])
return (mid+1);
// Check if mid itself is minimum element
if (mid > low && arr[mid] < arr[mid - 1])
return mid;
// Decide whether we need to go to left half or
// right half
if (arr[high] > arr[mid])
return countRotations(arr, low, mid-1);
return countRotations(arr, mid+1, high);
}
// Driver code
public static void main(String arg[])
{
int arr[] = {7, 9, 11, 12, 5};
int n = arr.length;
int cout = countRotations(arr, 0, n-1);
System.out.println(cout);
}
}