binarySearch

java

public class Hello
{
  public static int binarySearch(int[] a, int key)
  {
    int lo=0, hi = a.length-1;
    while(lo <= hi)
    {
      int mid = lo + (hi - lo) / 2;
      if(key < a[mid]) hi = mid-1;
      else if(key > a[mid]) lo = mid+1;
      else return mid;
    }
    return -1;
  }

  public static void main(String[] args)
  {
    int[] a = new int[] {3, 4,5,6,7,8};
    System.out.println(binarySearch(a, 5));
  }
}

 

posted @ 2013-02-21 15:07  wouldguan  阅读(121)  评论(0编辑  收藏  举报