日期:2014-05-20 浏览次数:20821 次
/*
* @project practice_j2se
* @file_name BinarySearch.java
*/
package com.j2se.exec.way;
/**
* @author jhb
* @version 1.0
* @create_on Oct 20, 2007 6:46:10 PM
*/
public class BinarySearch {
public static void main(String[] args) {
int[] array = new int[10];
for (int i = 0; i < 10; i++)
array[i] = (i + 1) * 10;
int aimEle = 100;
int position = new BinarySearch().search(array, aimEle, 0, 9);
if (position == -1)
System.out.println("找不到目标元素!");
else
System.out.println("目标" + aimEle + "的下标为:" + position);
}
public int search(int[] gather, int aim, int left, int right) {
int mid = (left + right) / 2;
if (aim == gather[mid])
return mid;
if (left == right)
return -1;
if (aim < gather[mid])
right = mid - 1;
if (aim > gather[mid])
left = mid + 1;
return search(gather, aim, left, right);
}
}