package com.chenjun.mysite.module.sys.service; /** * * @author Administrator * */ public class 二分查找类2 { private static final int size = 10; public static void main(String[] args) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = (2 * i) + 1; } // 1,3,5,7,9,11 for (int i = 0; i < size; i++) { System.out.print(a[i] + ","); } System.out.println("最终下标 " + binarySearch(7, a, 0, size - 1)); } // 返回找到的下标 public static int binarySearch(int number, int[] arr, int 小下标, int 大下标) { int 中间下标 = (大下标 + 小下标) / 2; if (number > arr[中间下标]) { 小下标 = 中间下标 + 1; // 递归 return binarySearch(number, arr, 小下标, 大下标); } else if (number < arr[中间下标]) { 大下标 = 中间下标 - 1; return binarySearch(number, arr, 小下标, 大下标); } else { return 中间下标; } } }
JDK1.7里面的实现,源自Arrays.class文件
1
private static int binarySearch0(long[] a, int fromIndex, int toIndex, long key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; long 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. }