二分法查找
二分法查找:g为猜测位置,l为左边界,r为右边界,
function bsearch(A, x) {
let l = 0, //查询范围的左边界
r = A.length-1, //查找范围的右边界
guess //猜测位置
while (l <= r){
guess = Math.floor((l+r)/2)
//循环不变式
//guess等于l,r中间位置
//l:查找范围左,r:查找范围右
if(A[guess]===x) return guess
else if(A[guess]>x) r = guess -1
else l = guess +1
//循环不变式
//l:新查找范围左,r:新查找范围右
}
return -1
}
const A =[3,5,6,7,9,22,25,44,65,78,98,99];
console.log(bsearch(A, 88))
console.log(bsearch(A,68))
console.log(bsearch(A,98))
结果:
-1
-1
10
插入排序
JavaScript原始实现
const A = [2,4,7,9,13]
const x = 8
const b = A.find(a => a > x)
const index = A.indexOf(b)
A.splice(index ===-1?A.length:index, 0, x)
function insert(A, i, x) {
//p指向下一个需要比较的元素
//p+1 指向空位
let p = i-1
while(p >= 0 && A[p] > x){
A[p+1] = A[p];
p--
}
A[p+1] = x;
}
function insertion_sort(A) {
for(let i = 1; i<A.length;i++){
insert(A, i, A[i])
}
}
const C = [5,8,1,3,9,12,18,32]
insertion_sort(C)
console.log(C)