[源码]排序数组二分法(折半)查找
对于已排序的数组,二分法是一种很简单、有效的查找方式,算法复杂度为O(log2n);
代码:
package alg;public class Bisection {public static int bisectionSearch(int value,int[] array) {int minIndex = 0;int curIndex = 0;int maxIndex = array.length - 1;int count = 0;// 用于循环次数记数int result = -1;if (value == array[maxIndex]) {result = maxIndex;} else if (value == array[minIndex]) {result = minIndex;} else {while(true) {// 如果两者相同或相邻,由于二者的值(除首次)均来自于已与value比较不等的值,因此数组中没有该值。if (2 > maxIndex - minIndex) {result = -1;break;}curIndex = minIndex + (maxIndex - minIndex) / 2;if (array[curIndex] == value) {result = curIndex;break;} else if (array[curIndex] < value) {minIndex = curIndex;} else {maxIndex = curIndex;}count++;}}System.out.println("loops = " + count);return result;}public static void main(String[] args) {int num = 1000;int value = 0;int[] array = new int[num];for (int i = 0; i < num; i++) {array[i] = i;}System.out.println("value = " + value + " at index " + bisectionSearch(value,array) + " of array.");}}Author:Pirate Leo