1.使用js实现二分查找
// 非递归的方式
function search(arr, key) { var start = 0; var end = arr.length - 1 while (start <= end) { var mid = parseInt((start + end) / 2) if (key === arr[mid]) { return mid } else if (key > arr[mid]) { start = mid + 1 } else { end = mid - 1 } } return -1 }var arr = [0, 13, 21, 35, 46, 52, 68, 77, 89, 94]; console.log(search2(arr, 94));
// 递归的方式
function search2(arr, key, start = 0, end = arr.length - 1) { var mid = parseInt((start + end) / 2) if (key > arr[mid]) { return search2(arr, key, mid + 1, end) } else if (key < arr[mid]) { return search2(arr, key, start, mid - 1) } else if (key === arr[mid]) { return mid } else { return -1 } }
var arr = [0, 13, 21, 35, 46, 52, 68, 77, 89, 94]; console.log(search2(arr, 94));
标签:arr,end,mid,start,key,search2,手写 From: https://www.cnblogs.com/zjy1017/p/17659986.html