二分查找JAVA实现

package kpp.search;
/**
 * 二分查找
 * 针对有序序列
 * @author kpp
 *
 */
public class BinarySearch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int data[] = {1,2,3,4,5,6,7,8,9,10};
        int key = 2;
        int index = search(data,key);
        
        if(index == -1){
            System.out.println("查找失败");
        }else{
            System.out.println("查找成功,key在数组的第"+index+"个位置(从0开始)");
        }
    }
    private static int search(int data[],int key){
        int left = 0;
        int right = data.length -1;
        while(left <= right){
            int mid = (left+right)/2;
            if(key < data[mid]){
                right = mid - 1;
            }else if(key > data[mid]){
                left = mid + 1;
            }else{
                return mid;
            }
        }
        return -1;
    }

}

 

posted @ 2015-03-31 11:30  kpp  阅读(186)  评论(0编辑  收藏  举报