You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionbubbleSort(arr,callback){if(Object.prototype.toString.call(arr)!=='[object Array]'){throw'bubbleSort: is not array';}if(typeofcallback==='undefined'){callback=function(a,b){returna-b;}}varorigin=arr.slice(),length=origin.length,count=0,start=0;while(start<length-1){varflag=true;for(varj=0;j<length-1-start;j++){if(callback(origin[j],origin[j+1])>0){flag=false;vartemp=origin[j];origin[j]=origin[j+1];origin[j+1]=temp;count++;}}if(flag)break;for(vark=length-1;k>=0;k--){if(callback(origin[k-1],origin[k])>0){flag=false;vartemp=origin[k];origin[k]=origin[k-1];origin[k-1]=temp;count++;}}if(flag)break;start++;}console.log(count);//32returnorigin;}
这样的实现对传入的参数进行了检测,并且可以根据callback来从小到大或者从大到小进行排序
The text was updated successfully, but these errors were encountered:
冒泡排序
图片详解
代码实现
假设有一个数组
var list = [22, 90, 65, 34, 27, 8, 43, 24, 9, 10, 100, 1001]
一阶段
要想实现冒泡肯定得来个双重循环结构,遍历到每个数和其之后的数进行比较,如果符合预期则进行交换,代码如下,计数
count
来表示交换的次数二阶段
有了一阶段的代码我们已经初步封装了一个
bubbleSort
的冒泡排序函数,你只要传入一个数组就能返回给你一个排序好的数组,但是这个是有局限性的好,我们再根据这个局限性封装下
这样的实现对传入的参数进行了检测,并且可以根据callback来从小到大或者从大到小进行排序
The text was updated successfully, but these errors were encountered: