Java实现二分查找算法
二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。所以在采用二分法查找时,数据需是有序不重复的,如果是无序的也可通过选择排序、冒泡排序等数组排序方法进行排序之后,就可以使用二分法查找。
基本思想:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止,但是如果当前段的索引最大值小于当前段索引最小值,说明查找的值不存在,返回-1,不继续查找。
下面贴出代码实现:
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;
}
}
最后更新于 2019-01-25 23:25:27 并被添加「java 二分查找 算法」标签,已有 47 位童鞋阅读过。
本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处,且在文章页面明显位置给出原文连接
此处评论已关闭