折半查找法例題分析?
package com.aozhi.test;
public class BinarySearch {
/*
* 循環(huán)實(shí)現(xiàn)二分查找算法arr[] 已排好序的數(shù)組x
* return 返回索引下標(biāo)
*/
public static int binarySearch(int[] arr, int x) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {//判斷非空
int middle = (low + high) / 2;//折半從中間開始
if (x == arr[middle]) {//是中間的直接返回
return middle;
} else if (x < arr[middle]) {//因?yàn)樗怯行虻臄?shù)組,可以根據(jù)中間值作比較
high = middle - 1;
} else {
low = middle + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };
System.out.println("循環(huán)查找:" + (binarySearch(arr, 6)));
}
}