检索算法——二分查找
如果要查找的数据是有序的, 二分查找算法比顺序查找算法更高效。
function insertionSort(arr) { var temp, inner; for ( var outer = 1; outer < arr.length; ++outer) { temp = arr[outer]; //选中一个值作为临时值,使得其前面的数依次与它进行比较 inner = outer; while (inner > 0 && (arr[inner - 1] >= temp)) { arr[inner] = arr[inner - 1]; --inner; } arr[inner] = temp; } } function prints(arr) { for ( var i = 0; i < arr.length; i++) { document.write(arr[i] + " "); if (i > 0 && i % 10 == 0) { document.write("<br />"); } } } function binSearch(arr, data) { var upperBound = arr.length - 1; var lowerBound = 0; 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; } var nums = []; for ( var i = 0; i < 100; ++i) { nums[i] = Math.floor(Math.random() * 101); } insertionSort(nums); prints(nums); var val = 45; var retVal = binSearch(nums, val); if (retVal >= 0) { document.write(" 已找到 " + val + " , 所在位置为: " + retVal); } else { document.write(val + " 没有出现在这个数组中。 "); } function count(arr, data) { //为什么需要count()———>在二分查找中要是有三个要查找的值,那么binSearch()方法仅会返回中间值所在的位置 var count = 0; var position = binSearch(arr, data); if (position > -1) {//判断是否在数组中找到data ++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; } alert(count(nums, val));