-
Notifications
You must be signed in to change notification settings - Fork 7
/
demo17.txt
51 lines (46 loc) · 1.03 KB
/
demo17.txt
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
package chapter8;
//在数组中找到一个局部最小的位置
public class demo17 {
/**
这个最小值并不是唯一的,只要符合要求即可.
主要是为了练习二分法
*/
public static void main(String[] args) {
int[] arr = {1,0};
int[] arr1 = {0,1};
int[] arr2 = {0,1,9,3};
int res2 = findMin(arr2);
int res = findMin(arr);
int res1 = findMin(arr1);
System.out.println(res+" "+res1+" "+res2);
}
public static int findMin(int[] arr){
if(arr==null || arr.length==0){
return -1;
}
if(arr.length==1){
return arr[0];
}
if(arr[1]>arr[0]){
return arr[0];
}
if(arr[arr.length-2]>arr[arr.length-1]){
return arr[arr.length-1];
}
//用二分法来处理,找这个局部最小值,二分法不一定要用在有序数组中
int left = 1, right = arr.length-2,mid = 0;
while(left<right){
mid = (left+right)/2;
if(arr[mid-1]>arr[mid]){
right = mid-1;
}
else if(arr[mid+1]<arr[mid]){
left = mid+1;
}
else{
return mid;
}
}
return left;
}
}