二分查找代码:
package net.liuyx.algorithm; public class BinarySearch { /** * @param args */ public static void main(String[] args) { int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; System.out.println(binarySearch(a, 0, a.length, -5)); } private static int binarySearch(int[] a, int start, int len, int key) { int low = start - 1, high = start + len, guess; while (high - low > 1) { guess = (high + low) / 2; if (a[guess] < key) low = guess; else if (a[guess] == key) return guess;// 提前返回这个索引值 else high = guess; } // 有一点需要注意的是,必须先判断key不在数组范围内的情况,不然的话,假如先执行return high,也就是判断if(a[high] == // key),此时会导致数组越界异常 if (high == start + len || low == start - 1)// key不在排好序的这个数组范围内 return ~high;// 按位非运算,有个好处,当~high=-1时,知道所需查找的数小于这个数组的范围,当~high = // -(a.length+1),时,我们可以知道所需查找的key大于这个数组范围 else return high;// 刚好high等于0或者等于a.length - 1的时候,即key等于数组的起始位置或终了位置 } }