forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotatedIndex.java
55 lines (46 loc) · 1.64 KB
/
RotatedIndex.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
package com.rampatra.arrays;
/**
* @author rampatra
* @since 2019-04-04
*/
public class RotatedIndex {
private static int findIndexOfRotationPoint(String[] words) {
return findIndexOfRotationPoint(words, 0, words.length - 1);
}
private static int findIndexOfRotationPoint(String[] words, int start, int end) {
if (start > end) return -1;
int mid = (start + end) / 2;
if (mid == 0 || mid == words.length - 1) return -1;
if (words[mid].compareTo(words[mid - 1]) < 0 && words[mid].compareTo(words[mid + 1]) < 0) {
return mid;
} else if (words[mid].compareTo(words[mid - 1]) > 0 && words[mid].compareTo(words[mid + 1]) < 0) {
return findIndexOfRotationPoint(words, start, mid - 1);
} else {
return findIndexOfRotationPoint(words, mid + 1, end);
}
}
public static void main(String[] args) {
System.out.println(findIndexOfRotationPoint(new String[]{
"ptolemaic",
"retrograde",
"supplant",
"undulate",
"xenoepist",
"asymptote", // <-- rotates here!
"babka",
"banoffee",
"engender",
"karpatka",
"othellolagkage",
}));
System.out.println(findIndexOfRotationPoint(new String[]{}));
System.out.println(findIndexOfRotationPoint(new String[]{
"asymptote",
"babka",
"banoffee",
"engender",
"karpatka",
"othellolagkage",
}));
}
}