package foo; import java.util.Arrays; public class Main { /** * 二分查找 * @param key 搜索的目标 * */ private static int binarySearch(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; int mid, midVal; while (low <= high) { mid = (low + high) >>> 1; midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } public static void main(String[] args) throws Exception { int[] a = new int[]{1,2,3,4,5}; System.out.println(binarySearch(a, 0, a.length, 0)); System.out.println(binarySearch(a, 0, a.length, 1)); System.out.println(binarySearch(a, 0, a.length, 2)); System.out.println(binarySearch(a, 0, a.length, 3)); System.out.println(binarySearch(a, 0, a.length, 4)); System.out.println(binarySearch(a, 0, a.length, 5)); System.out.println(binarySearch(a, 0, a.length, 6)); } }
折半查找法也称为二分查找法,它充分利用了元素间的次序关系,采用分治策略,可在最坏的情况下用O(log n)完成搜索任务。优点是比较次数少,查找速度快,平均性能好;其缺点是要求待查表为有序表,插入删除困难。因此,折半查找方法适用于不经常变动而查找频繁的有序列表。