算法图解笔记:第一章(java版)

二分查找:

优点:时间复杂度低,仅为logN

注意:前提是有序数组

Code:

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
public class Code_01_binarySearch {
public static void main(String[] args) {
//测试数组
int[] myList = {1,3,5,7,9};
System.out.println(binarySearch(myList, 7));
System.out.println(binarySearch(myList, 10));
}

public static int binarySearch(int[] list,int item){
int low = 0;
int high = list.length - 1;
while(low <= high){
//定义中间位置
int mid = low +(high - low)/2;
int guess = list[mid];
if(guess == item){
return mid;
}
if(guess < item){
low = mid + 1;
}
else{
high = mid - 1;
}
}
return -1;
}

}
© 2021 XuXing's blog All Rights Reserved. 本站访客数人次 本站总访问量
Theme by hiero