forked from IDeserve/learn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindElementSortedRotatedArray
105 lines (83 loc) · 2.48 KB
/
FindElementSortedRotatedArray
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
95
96
97
98
99
100
101
102
103
104
105
package binarysearch;
/**
* <b>IDeserve <br>
* <a href="https://www.youtube.com/c/IDeserve">https://www.youtube.com/c/IDeserve</a>
* <br><br>
* Find an element in sorted rotated array</b><br>
* Given a sorted rotated integer array and an integer, find the index of the integer in the array. If not found, return -1.
*
* Example: <br>
* array = { 97, 108, 149, 21, 32, 43, 74, 75, 86 }
* <br>
* integer = 43
* <br>
* Output: 5
* <br><br>
* <a href="https://www.youtube.com/watch?v=6pSzsJH56BA">Find an element in a sorted rotated array Youtube Link</a>
* @author Saurabh
*
*/
public class FindElementSortedRotatedArray {
public static int findElementInSortedRotatedArray(int array[], int num) {
if (array == null || array.length == 0) {
return -1;
}
int pivot = findPivot(array);
if (pivot > 0 && num >= array[0] && num <= array[pivot - 1]) {
return binarySearch(array, 0, pivot - 1, num);
} else {
return binarySearch(array, pivot, array.length - 1, num);
}
}
public static int findPivot(int[] array) {
if (array == null || array.length == 0) {
return -1;
}
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 ( array[mid] > array[mid + 1]) {
return mid + 1;
} else if (array[start] <= array[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
return 0;
}
public static int binarySearch(int[] array, int start, int end, int num) {
if (array == null || array.length == 0) {
return -1;
}
if(start > end || start < 0 || end >= array.length) {
throw new IllegalArgumentException("Invalid values for start and end! start = " + start + ", end = " + end);
}
if(num < array[start] || num > array[end]) {
return -1;
}
while (start <= end) {
int mid = (start + end) / 2;
if (array[mid] == num) {
return mid;
} else if (num < array[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int array[] = { 156, 235, 457, 21, 32, 43, 74, 75, 86, 97, 108, 149 };
findElementInSortedRotatedArrayTest(array, 43);
}
private static void findElementInSortedRotatedArrayTest(int[] array, int num) {
int index = findElementInSortedRotatedArray(array, num);
System.out.println("Element " + num + (index >= 0 ? (" found at index " + index) : " not found!"));
}
}