Java实现二分查找算法

二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。所以在采用二分法查找时,数据需是有序不重复的,如果是无序的也可通过选择排序、冒泡排序等数组排序方法进行排序之后,就可以使用二分法查找。
基本思想:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止,但是如果当前段的索引最大值小于当前段索引最小值,说明查找的值不存在,返回-1,不继续查找。

下面贴出代码实现:

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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
* Created by Sam on 18/12/9.
*/
public class Test {
public static void main(String[] args) {

int[] array = {1,4,7,9,12,56,78,89,120,179,180,200,290};
System.out.println("index="+binarySearch(array,290));
}

public static int binarySearch(int[] array,int searchNumber){

int minIndex = 0;
int maxIndex = array.length - 1;

int searchIndex = (minIndex + maxIndex) >> 1 ;
int count = 0;

while (array[searchIndex] != searchNumber){

System.out.printf("第次%d次运算\n", ++count);

if (array[searchIndex] > searchNumber){
maxIndex = searchIndex - 1 ;
}else {
minIndex = searchIndex + 1 ;
}

if (minIndex>maxIndex){
return -1;
}

searchIndex = (minIndex + maxIndex) >> 1 ;
}
return searchIndex;
}

}
  • 作者: Sam
  • 发布时间: 2019-01-25 23:26:42
  • 最后更新: 2019-12-09 23:03:26
  • 文章链接: https://ydstudios.gitee.io/post/e486e255.html
  • 版权声明: 本网所有文章除特别声明外, 禁止未经授权转载,违者依法追究相关法律责任!