Skip to content

Commit 8a8b10f

Browse files
authored
Merge pull request #63 from Amrutha26/main
Rotated Binary Search
2 parents 492e182 + ddb9efa commit 8a8b10f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

PeakIndex.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//https://leetcode.com/problems/peak-index-in-a-mountain-array/
2+
3+
class Solution {
4+
public int peakIndexInMountainArray(int[] arr) {
5+
int start = 0;
6+
int end = arr.length - 1;
7+
8+
while(start < end) {
9+
int mid = start + (end - start) / 2;
10+
if(arr[mid] > arr[mid+1]) {
11+
// you are in dec part of the array
12+
// this may be the ans, but look at left
13+
end = mid;
14+
} else {
15+
// arr[mid + 1] > arr[mid]
16+
// you are in inc part of the array
17+
start = mid + 1;
18+
}
19+
}
20+
21+
// In the end, start == end and pointing to the largest number because of the 2 checks
22+
// start and end are always trying to find max element in the above 2 checks
23+
// hence, when they are pointing to just one element, that is the max element
24+
// At every point of time of start and end, there may be a best possible ans at that particular time
25+
return end;
26+
}
27+
}

RotatedBinarySearch.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class RBS {
2+
public static void main(String[] args) {
3+
4+
5+
}
6+
7+
static int search(int[] arr, int target, int s, int e) {
8+
if(s > e) {
9+
return -1;
10+
}
11+
12+
int m = s + (e-s) / 2;
13+
if(arr[m] == target) {
14+
return m;
15+
}
16+
17+
if(arr[s] <= arr[m]) {
18+
if(target >= arr[s] && target <= arr[m]) {
19+
return search(arr, target, s, m-1);
20+
} else {
21+
return search(arr, target, m+1, e);
22+
}
23+
}
24+
25+
if(target >= arr[m] && target <= arr[e]) {
26+
return search(arr, target, m+1, e);
27+
}
28+
29+
return search(arr, target, s, m-1);
30+
}
31+
}

0 commit comments

Comments
 (0)