JavaScript搜索算法

1-顺序搜索 最基本、最低效的搜索算法

将每一个数据结构中的元素与要找的元素做比较

this.sequentialSearch = function(item){

for( var i=0; i<array.length; i++){

if( item==array[i] )

return i;

}

return -1;

};

2-二分搜索

这个算法要求被搜索的数据结构已排序:

a-选择数组中间值;

b-如果选中值是待搜索值,算法执行完毕;

c-如果待搜索值比选中值小,则返回a并在选中值左边的子数组中寻找;

d-如果待搜索值比选中值大,则返回a并在选中值右边的子数组中寻找。

this.binarySerach= function(item){

this.quickSort(); //排序

var low= 0,

high= array.length-1,

mid,

element;

while( low<=high){

mid= Math.floor( (low+high)/2 );

element= array[mid];

if( element<item ){

low= mid+1;

} else if( element>item){

high= mid-1;

} else {

return mid;

}

}

return -1;

};

时间复杂度:

算法

数据结构

最差情况

顺序排序

数组

O(n)

二分搜索

已排序的数组

O( log(n) )

深度优先搜索DPS

顶点数为|V|,边数为|E|的图

O( |V|+|E| )

广度优先搜索BFS

顶点数为|V|,边数为|E|的图

O( |V|+|E| )

猜你喜欢

转载自blog.csdn.net/D_C_Hao/article/details/84946243
今日推荐