二分查找法 Python 实现:
def binary_search(list, item): low = 0 high = len(list)—1 while low <= high: mid = (low + high) guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None my_list = [1, 3, 5, 7, 9] print binary_search(my_list, 3) # => 1 print binary_search(my_list, -1) # => None
二分查找法 JavaScript 实现:
function binary_search(arr, item){ var left = 0; var right = arr.length-1; while(left <= right){ var mid = Math.floor((left+right)/2); if(item == arr[mid]){ return mid; }else if(item > arr[mid]){ left = mid + 1; }else{ right = mid - 1; } } return false; } var arr=[-34, 1, 3, 4, 5, 8, 34, 45, 65, 87]; console.log(binary_search(arr,5)); //4
参考:《算法图解》
修改时间 2023-11-02
声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。