二分查找

func findTarget(numbers [] int , target int ,left int) int{
    right := len(numbers) - 1
    result := -1
    for left <= right{
        mid := left + (right - left)/2
        if numbers[mid] < target{
            left = mid + 1
        }else if numbers[mid] > target{
            right = mid -1
        }else {
            result = mid
            break
        }
    }
    return result
}

 

java

public static int binarySearch(int[] arr, int start, int end, int hkey){
    int result = -1;

    while (start <= end){
        int mid = start + (end - start)/2;    //防止溢位
        if (arr[mid] > hkey)
            end = mid - 1;
        else if (arr[mid] < hkey)
            start = mid + 1;
        else {
            result = mid ;  
            break;
        }
    }

    return result;

}

 

posted @ 2019-09-23 09:06  式微胡不归  阅读(135)  评论(0编辑  收藏  举报