给定一个有序数列可以采用二分查找,如果找到返回数组下标值,如果没找到返回-1.

import java.util.Scanner;
import java.util.Vector;

/**
 * Created by Kaiming Wan on 2015/10/26 0026.
 */
public class BSearch {

    public static int binarySearch(int[] a,int left,int right,int item){


        int mid = (right+left)/2;
        if(a[mid]==item) return mid;        //如果中间的值就是,则之间返回

        if(right-left==0) return -1;        //出递归条件是只剩1个数的时候,这时候right==left,并且已经确认过a[mid]!=item,可以退出循环

        if(item < a[mid]) return binarySearch(a,left,mid-1,item);
        else return binarySearch(a,mid+1,right,item);
    }

    public static void main(String[] args){

        int[] a = {1,2,3,4,5,6,7,8,9,10};           //随便设定10个已经升序排好的数
        int index = binarySearch(a,0,a.length-1,5);
        System.out.println(index);
    }

}