二分查找算法
1 /* 2 * 二分查找算法 3 */ 4 public class BinarySerach { 5 public static int binarySearch(int[] list, int key) { 6 int low = 0; 7 int high = list.length - 1; 8 while (high >= low) { 9 int mid = (low + high) / 2; 10 if (key == list[mid]) 11 return mid; 12 else if (key < list[mid]) 13 high = mid - 1; 14 else 15 low = mid + 1; 16 } 17 return -low - 1; 18 } 19 20 public static void main(String[] args) { 21 int[] list = { 2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70 }; 22 int lb = binarySearch(list, 10); 23 System.out.println("查找的值是: " + list[lb] + " 位置在第" + lb + "位"); 24 } 25 }