这篇文章主要介绍JavaScript中二分查找法和计算重复次数的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
具体如下:
javascript数据结构与算法---检索算法(二分查找法、计算重复次数)
function qSort(arr){
if (arr.length == 0) {
return [];
}
var left = [];//存储小于基准值
var right = [];//存储大于基准值
var pivot = arr[0];
for (var i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return qSort(left).concat(pivot, qSort(right));//递归
}
function binSearch(arr,data) {
var lowerBound = 0;
var upperBound = arr.length - 1;
while(lowerBound <= upperBound) {
var mid = Math.floor((upperBound + lowerBound)/2);
if(arr[mid] < data) {
lowerBound = mid + 1;
}else if(arr[mid] > data) {
upperBound = mid - 1;
}else {
return mid;
}
}
return -1;
}
function count(arr, data) {
var count = 0;
var position = binSearch(arr, data);
if (position > -1) {
++count;
for (var i = position-1; i > 0; --i) {
if (arr[i] == data) {
++count;
}
else {
break;
}
}
for (var i = position+1; i < arr.length; ++i) {
if (arr[i] == data) {
++count;
}
else {
break;
}
}
}
return count;
}
var nums = [90,43,49,15,23,2,70,23,20,95,69,23,29,26];
var list = qSort(nums);
console.log(list);
var findnum = 23;
console.log("需要查找的数据为: " + findnum);
var retVal = binSearch(list, findnum);
if (retVal >= 0) {
console.log( "找到 " + findnum + "的位置为: "+retVal);
}else {
console.log(" is not in array.");
}
console.log(findnum + "重复次数为"+count(list, findnum));
使用在线HTML/CSS/JavaScript代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试上述代码,可得如下运行结果:
以上是“JavaScript中二分查找法和计算重复次数的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!