二分法查找元素

二分查找的思想原理图解

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
70
71
72
73
74
75
76
77
78
79
/**
* 二分查找的前提: 数组元素必须有序.
* 如果数组元素无序,那么请使用基本查找
*/
public class BinarySearchDemo {

public static void main(String[] args) {

// 定义一个数组
int[] arr = {13, 24, 57, 69, 80} ;

// 调用方法
int index = binarySearch(arr , 80) ;

// 输出
System.out.println("index: " + index);

}

/**
* 二分查找
*/
private static int binarySearch2(int[] arr, int value) {

// 定义两个int类型的变量
int minIndex = 0 ;
int maxIndex = arr.length - 1 ;

while(minIndex <= maxIndex){

// 计算出中间索引
int midIndex = (minIndex + maxIndex) >>> 1 ;

// 比较
if(arr[midIndex] == value){
return midIndex ;
}else if(arr[midIndex] > value){
maxIndex = midIndex - 1 ;
}else if(arr[midIndex] < value){
minIndex = midIndex + 1 ;
}

}

return -1;
}


/**
* 二分查找
*/
private static int binarySearch(int[] arr, int value) {

// 定义两个int类型的变量
int minIndex = 0 ;
int maxIndex = arr.length - 1 ;

// 计算出中间索引
int midIndex = (minIndex + maxIndex) / 2 ;

while(minIndex <= maxIndex){

// 比较
if(arr[midIndex] == value){
return midIndex ;
}else if(arr[midIndex] > value){
maxIndex = midIndex - 1 ;
}else if(arr[midIndex] < value){
minIndex = midIndex + 1 ;
}

midIndex = (minIndex + maxIndex) / 2 ;

}

return -1;
}

}
-------------本文结束感谢您的阅读-------------
0%