Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions SearchInMountain.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@


public class SearchInMountain {
public static void main(String[] args) {

}

int search(int[] arr, int target) {
int peak = peakIndexInMountainArray(arr);
int firstTry = orderAgnosticBS(arr, target, 0, peak);
if (firstTry != -1) {
return firstTry;
}

return orderAgnosticBS(arr, target, peak+1, arr.length - 1);
}

public int peakIndexInMountainArray(int[] arr) {
int start = 0;
int end = arr.length - 1;

while (start < end) {
int mid = start + (end - start) / 2;
if (arr[mid] > arr[mid+1]) {

end = mid;
} else {

start = mid + 1;
}
}
return end;

}

static int orderAgnosticBS(int[] arr, int target, int start, int end) {

boolean isAsc = arr[start] < arr[end];

while(start <= end) {

int mid = start + (end - start) / 2;

if (arr[mid] == target) {
return mid;
}

if (isAsc) {
if (target < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (target > arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
}
return -1;
}
}