-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLc_33.java
More file actions
80 lines (64 loc) · 1.98 KB
/
Lc_33.java
File metadata and controls
80 lines (64 loc) · 1.98 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
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
// Lc-33. Search in Rotated Sorted Array
/* -first find pivot(largest number in the array)
-next apply binary search on first and second half to find the target
*/
public class Lc_33 {
public static void main(String[] args){
int[] arr = {3,4,5,6,7,1,2};
int target = 3;
int pivot = findPivot(arr);
//if pivot not found
if(pivot == -1){
System.out.println(binarySearch(0, arr.length-1, target, arr));
return;
}
if(arr[pivot] == target){
System.out.println(pivot);
return;
}
if(target >= arr[0]){
System.out.println(binarySearch(0, pivot-1, target, arr));
return;
}
System.out.println(binarySearch(pivot+1, arr.length-1, target, arr));
}
//find pivot
static int findPivot(int[] arr){
int start = 0, end = arr.length-1;
int mid ;
while(start <= end){
mid = start + (end - start) / 2;
// Case 1: mid is the pivot
if (mid < end && arr[mid] > arr[mid + 1]) {
return mid;
}
// Case 2: mid-1 is the pivot
if (mid > start && arr[mid] < arr[mid - 1]) {
return mid-1;
}
// Left side is unsorted (pivot must be there)
if (arr[mid] < arr[start]) {
end = mid - 1;
} else { // Right side is unsorted
start = mid + 1;
}
}
return -1; // No pivot found
}
//binary search
static int binarySearch(int start, int end, int target, int[] arr){
while(start <= end){
int mid = start + (end - start)/2;
if(target == arr[mid]) {
return mid;
}
else if(target > arr[mid]){
start = mid + 1;
}
else if(target < arr[mid]){
end = mid - 1;
}
}
return -1;
}
}