-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMountainOfArray.java
More file actions
69 lines (57 loc) · 1.38 KB
/
MountainOfArray.java
File metadata and controls
69 lines (57 loc) · 1.38 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
public class MountainOfArray {
public static int findelement(int[] a){
return 0;
}
public static int binarySearch(int[] a, int start, int end,int target){
if(start > end){
return -1;
}
int mid = (start+end)/2;
if(a[mid]==target){
return mid;
}
// if(mid==0){
// return -1;
// }
//
if(a[mid]<a[mid+1]){
if(a[mid]<target){
return binarySearch(a,start,mid-1,target);
}else{
return binarySearch(a,mid+1,start,target);
}
}else{
if(a[mid]<target){
return binarySearch(a,start,mid-1,target);
}else{
return binarySearch(a,mid+1,end,target);
}
}
}
public static int bpeakSearch(int[] a, int start, int end){
// if(start > end){
// return -1;
// }
int mid = (start+end)/2;
if(mid==0){
return -1;
}
if(a[mid]>a[mid-1]&&a[mid]>a[mid+1]){
return mid;
}
if(a[mid]<a[mid-1]&&a[mid]>a[mid+1]){
return bpeakSearch(a,start,mid-1);
}else{
return bpeakSearch(a,mid+1,start);
}
}
public static void main(String args[]){
//first binary search the max by comparing the item before and after, if the item is found
//just return, record the index of the max val.
//then cut the array, and then sort each part
int[] A = {1,2,3,4,5,3,1,0};
// System.out.println(bpeakSearch(A,0,7));
// System.out.println(binarySearch(A,0,4,0));
System.out.println(binarySearch(A,4,7,0)); //flip again
}
}