1.顺序搜索
顺序或线性搜索是最基本的搜索算法。它的机制是,将每一个数据结构中的元素和我们要找 的元素做比较。顺序搜索是最低效的一种搜索算法。
function search(arr,item) {
for(var i =0; i < arr.length; i++){
if(arr[i] == item){
return i
}
}
return -1
}
2.二分搜索
二分搜索算法的原理和猜数字游戏类似,就是那个有人说“我正想着一个1到100的数字”的 游戏。我们每回应一个数字,那个人就会说这个数字是高了、低了还是对了。
这个算法要求被搜索的数据结构已排序。(最好从小到大)
- 选择数组的中间值
- 如果选中值是待搜索值,那么算法执行完毕(值找到了)。
- 如果待搜索值比选中值要小,则返回步骤1并在选中值左边的子数组中寻找。
- 如果待搜索值比选中值要大,则返回步骤1并在选种值右边的子数组中寻找。
class TwoSearch {
constructor(arr,item) {
this.low = 0;
this.high = arr.length -1;
this.mid = null;
this.item = item;
this.element = null;
this.arr = arr;
}
binarySearch () {
while(this.low <= this.high){
this.mid = Math.floor((this.low + this.high) / 2 )
this.element = this.arr[this.mid] //中间值
if(this.element < this.item){
// 中间值小于搜索值那就要去右边的子数组中查找,重新计算中间值
this.low = this.mid + 1
}else if(this.element > this.item){
中间值大于搜索值那就要去左边的子数组中查找,重新计算中间值
this.high = this.mid - 1
}else{
return this.mid
}
}
return false
}
}
let two = new TwoSearch([1,2,3,4,5],5)
console.log(two.binarySearch()) // 4 (下标)