- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
Latest commit
42 lines (34 loc) · 817 Bytes
/
Copy pathBinarySearch.java
File metadata and controls
42 lines (34 loc) · 817 Bytes
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
packageyoozoo.day1;
importjava.util.Scanner;
publicclassBinarySearch {
publicstaticvoidmain(String[] args) {
//二分查找
inti = 0;
Scannerscan = newScanner(System.in);
intnum = scan.nextInt();
int[] arr = newint[num ]; //定义一个有序数组
while(i < num){
arr[i] = scan.nextInt();
i++;
}
inttarget = 5; //要在输入的数组里面查找5
intlow = 0;
inthigh = arr.length-1;
intj = binarysort(arr,low,high,target);
System.out.println(j + " " + arr[j]);
}
privatestaticintbinarysort(int[] arr, intlow, inthigh, inttarget) {
// 二分查找
while(low <= high){
intmid = (low + high)/2;
if(arr[mid] < target){
low = mid+1;
}elseif(arr[mid] > target){
high = mid-1;
}else{
returnmid ;
}
}
return -1;
}
}