检索算法
顺序查找
function seqSearch(arr, data) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] == data) {
return true;
}
}
return false;
}
查找最大值
function getMax(arr) {
if(arr.length == 0) {return}
var max = arr[0];
for(var i = 1; i < arr.length; i++) {
if(arr[i] > max) {
max = arr[i];
}
}
return max;
}
查找最小值
function getMin(arr) {
if(arr.length == 0) {return}
var min = arr[0];
for(var i = 1; i < arr.length; i++) {
if(arr[i] < min) {
min = arr[i];
}
}
return min;
}
二分查找(适用于有序数列)
function binSearch(arr, data) {
var upB = arr.length-1;
var downB = 0;
while(downB <= upB) {
var mid = Math.floor((upB + downB)/2);
if(arr[mid] < data) {
downB = mid + 1;
}
else if(arr[mid] > data) {
upB = mid - 1;
}
else {
return mid;
}
}
return -1;
}
计算重复次数
function repeatNum(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 j = position + 1; j < arr.length; j++) {
if(arr[j] == data) {
count++;
}else {
break;
}
}
}
return count;
}