package com.wj; public class BinarySearch { public static void main(String[] args) { int len = 10000; int[] a = new int[len]; for (int i = 0; i < len; ++i) { a[i] = i; } System.out.println(find(a, 56780)); System.out.println(find(a, 5678)); System.out.println(find2(a, 56780, 0, len - 1)); System.out.println(find2(a, 5678, 0, len - 1)); } private static int find(final int[] a, final int value) { int l = 0; int r = a.length - 1; while ( l <= r) { int mid = l + (r - l) / 2; if (a[mid] == value) { return mid; } else if (a[mid] < value) { l = mid + 1; } else { r = mid - 1; } } return -1; } private static int find2(final int[] a, final int value, final int l, final int r) { if (l > r) return -1; int mid = l + (r - l) / 2; if (a[mid] == value) { return mid; } else if (a[mid] < value) { return find2(a, value, mid + 1, r); } else { return find2(a, value, l, mid - 1); } } }