Skip to content

Search in a mountain program added #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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;
}
}