var data = [33, 86, 12, 9, 66, 5, 10, 45, 11, 3];
function sort(data){
var i=0;
while(idata[j+1]){
var x=data[j];
data[j]=data[j+1];
data[j+1]=x;
}
}
i++;
}
}
sort(data)
BinarySearch(data,33)
function BinarySearch(arr, target) {
let s = 0;
let e = arr.length - 1;
let m = Math.floor((s + e) / 2);
let sortTag = arr[s] <= arr[e];//确定排序顺序
while (s < e && arr[m] !== target) {
if (arr[m] > target) {
sortTag && (e = m - 1);
!sortTag && (s = m + 1);
} else {
!sortTag && (e = m - 1);
sortTag && (s = m + 1);
}
m = Math.floor((s + e) / 2);
}
if (arr[m] == target) {
console.log('找到了,位置%s', m);
return m;
} else {
console.log('没找到');
return -1;
}
}
网站栏目:使用冒泡法进行排序然后用二分查找法找出33的位置JS
文章起源:
http://njwzjz.com/article/ggodjj.html