二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
二分查找的要求:
1.数组的元素必须是升序排列或者是降序排列的;
2.查找的数量只能是一个,不能是多个
附上源代码:
/**
* 二分查找算法
* @author weichert
*/
public class BinarySort {
public static void main(String[] args) {
//创建一个升序排序好的数组用于存储需要进行二分查找的元素;
int[] arr = {1,3,5,7,9,11,13,16,25,26,39};
//确定需要查找的元素;
int target = 16;
//我们将需要进行二分查找的方法进行封装,方便接下来调用;
int index = binarySearch(arr,target);
//对得到的索引值进行判断;
if (index == -1) {
System.out.println("对不起,没有找到您想要的元素");
return;
}
System.out.println ("您要查找到的元素"+target+"的索引为:" + index);
}
private static int binarySearch(int[] arr, int target) {
//确定数组的左索引
int leftIndex = 0;
//确定数组的右索引
int rightIndex = arr.length - 1;
//确定数组的中间索引
int centerIndex;
//使用while循环,进行判定
while (leftIndex < rightIndex) {
centerIndex = (leftIndex + rightIndex) >>> 1;
//判断是否命中我们的目标值;
if (arr[centerIndex] == target) {
//返回查找到的数组元素的索引;
return centerIndex;
}
//当中间索引的值大于目标值的时候,说明目标值在中间索引的左边;
if (arr[centerIndex] > target) {
//将中间索引的值赋值给右索引;
rightIndex = centerIndex;
}
//当中间索引的值小于目标值的时候,说明目标值在中间索引的右边;
if (arr[centerIndex] < target) {
//将中间索引的值赋值给左索引;
leftIndex = centerIndex;
}
}
//当未查找到所需要的元素时,返回-1;
return -1;
}
}
备注已经非常的详细,有问题可以在评论区进行留言哦!