二分查找
前提:数组已经有序
每次都拿中间索引的值和其他索引的值进行比较,如果相等,就返回中间元素的索引
如果比要找的数小,说明要找的数在中间索引的右边,改变查找范围的左边界,将左边界变成原数组的中间位置
如果必要查找的数大,说明要找的数在中间索引的左边,改变查找范围的右边界,将右边界变成数组的中间位置
package com.nim.day15;
/*
* 二分查找
* 折半查找
* 前提条件:查找的数组必须是有序的
* 每次都用中间的元素和要找的元素进行比较
*/
public class BinarySearchDemo {
public static void main(String[] args) {
int[] arr = {1,3,5,7,9,10,14};
int index = binarySearch(arr,6);
if(index < 0){
System.out.println("no such element");
}else{
System.out.println("index is:" + index);
}
}
//自定义二分查找方法(需不需要返回值;有没有参数)
public static int binarySearch(int[] arr, int value){
int min = 0;
int max = arr.length - 1;
int mid = (min + max)/2;
//不知道比较的次数,用while循环
while(arr[mid] != value){
//判断要找的数落在左边还是右边
if(arr[mid] < value){
min = mid + 1;
}else if(arr[mid] > value){
max = mid - 1;
}else{
return mid;
}
//重新设定中间的索引值
mid = (min + max)/2;
//设定循环中指条件
if(min > max){
return -1;
}
}
return mid;
}
}