JS排序方法(sort,bubble,select,insert)代码汇总_基础知识
程序员文章站
2022-04-12 23:25:10
...
最近开始学习数据结构。
一点一点整理,希望能坚持下来。
因为方向是前端,所以用JavaScript实现。
//sort排序 var testArr1=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; var testArr2=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; var testArr3=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; testArr1.sort();//排序结果:[15, 19, 2, 26, 27, 3, 36, 38, 4, 44, 46, 47, 48, 5, 50] testArr2.sort(function(a,b){return a>b});//排序结果:[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50] testArr3.sort(function(a,b){return a-b});//排序结果:[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
//Bubble排序
var testArr1=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; var testArr2=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; function bubbleSort1(array){ for(i=array.length-1;i>0;i--){ for(j=0;j0;i--){ for(j=0;j
//Select排序
var testArr=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; function selectSort(array){ for(i=0;i
//Insert排序
var testArr=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48]; function insertSort(array){ for (var i = 0 ; i = 0; j--) { if(curElement