【笔记】二分法,有序数组中快速寻找某个元素的下标
程序员文章站
2024-03-17 14:57:22
...
function indexOfSorted(arr,n){
var low = 0;
var high = arr.length - 1;
var mid = Math.ceil((low + high) / 2);
console.log(mid);
while(high > low){
if(n == arr[low]){return low;}
if(n == arr[high]){return high;}
if(n == arr[mid]){return mid;}
if(n > arr[mid]){ low = mid; mid = Math.ceil((low + high) / 2); }
if(n < arr[mid]){ high = mid; mid = Math.ceil((low + high) / 2); }
}
}
var sortedArr = [1,4,7,9,11,12,21,26,33];
console.log(indexOfSorted(sortedArr,12));
上一篇: 二分查找【c语言】
下一篇: 牛客网:吃货 (二分模拟)