顺序搜索
按照顺序从前往后搜索
时间复杂度:O(N)
Array.prototype.sequentialSearch = function(item){
for(let i = 0; i<this.length;i++) {
if(this[i] === item) {
return i
}
}
return -1
}
const res = [1, 2, 3, 4, 5].sequentialSearch(3);
二分搜索
从数组的中间元素开始,如果中间元素正好是目标值,则搜索结束。
如果目标值大于或者小于中间元素,则在大于或小于中间元素的那一半数组中搜索。
时间复杂度:O(logN)
Array.prototype.binarySearch = function (item) {
// this.sort()
let low = 0;
let height = this.length - 1;
while (low <= height) {
const mid = Math.floor((low + high) / 2);
const element = this[mid];
if (element < item) {
low = mid + 1;
} else if (element > item) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
};
const res = [1, 2, 3, 4, 5].binarySearch;