js-排序算法
之前和一个小伙伴谈起了排序算法,所以我抽时间整理了大家平时常见的一些排序算法。
1、冒泡算法:
1 <script> 2 function sortMP(ele) { 3 for (var i = 0; i < ele.length - 1; i++) { 4 for (j = 0; j < ele.length - i - 1; j++) { 5 if (ele[j] > ele[j + 1]) { 6 var swap = ele[j]; 7 ele[j] = ele[j + 1]; 8 ele[j + 1] = swap; 9 } 10 } 11 } 12 return ele; 13 } 14 var ele = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; 15 console.log(sortMP(ele)); 16 </script>
冒泡排序动图演示
2、选择排序:
1 <script> 2 function selectSort(arr) { 3 var len = arr.length; 4 var minIndex, temp; 5 console.time('选择排序耗时'); 6 for (var i = 0; i < len; i++) { 7 minIndex = i; 8 for (var j = i + 1; j < len; j++) { 9 if (arr[j] < arr[minIndex]) { //寻找最小的数 10 minIndex = j; //将最小的数的索引进行保存 11 } 12 } 13 temp = arr[i]; 14 arr[i] = arr[minIndex]; 15 arr[minIndex] = temp; 16 } 17 console.timeEnd('选择排序耗时'); 18 return arr; 19 } 20 var arr = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; 21 console.log(selectSort(arr)); 22 </script>
选择排序动图演示
3、插入排序:
<script> function sortCR(ele) { //假设第0个元素是一个有序的数列,第1个以后的是无序的序列 //所以从第一个元素开始将无序数列的元素插入到有序数列中 for (var i = 1; i < ele.length; i++) { if (ele[i] < ele[i - 1]) { //取出无序数列中的第i个作为被插入元素 var guard = ele[i]; //记住有序数列的最后一个位置,并且将有序数列位置扩大一个 var j = i - 1; ele[i] = ele[j]; //比大小,找出被插入元素所在的位置 while (j >= 0 && guard < ele[j]) { ele[j + 1] = ele[j]; j--; } ele[j + 1] = guard; //插入 } }
return ele; } var ele = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; console.log(sortCR(ele)); </script>
插入排序动图演示
4、快速排序:
1 <script> 2 function quickSort(ele) { 3 if (ele.length <= 1) { 4 return ele; 5 } 6 var privotIndex = Math.floor(ele.length / 2); 7 // alert(ele.length); 8 var privot = ele.splice(privotIndex, 1)[0]; 9 //alert(privot); 10 var left = []; 11 var right = []; 12 for (var i = 0; i < ele.length; i++) { 13 if (ele[i] <= privot) { 14 left.push(ele[i]); 15 } else { 16 right.push(ele[i]); 17 } 18 } 19 return quickSort(left).concat([privot], quickSort(right)); 20 } 21 var ele = [3,44,38,5,47,15,36,26,27,2,46,4,19,50,48]; 22 console.log(quickSort(ele)); 23 </script>
快速排序动图演示
5、希尔排序:
1 <script> 2 //希尔排序实际上是分组插入排序,该方法又称速效增量排序 3 function shallSort(arr) { 4 var increment = arr.length; 5 var i; 6 var temp; 7 var count = 0; 8 do { 9 //设置增量 10 increment = Math.floor(increment / 3) + 1; 11 for (i = increment; i < arr.length; i++) { 12 console.log(increment); 13 if (arr[i] < arr[i - increment]) { 14 temp = arr[i]; 15 for (var j = i - increment;j >= 0 && temp < arr[j];j -= increment){ 16 arr[j + increment] = arr[j]; 17 } 18 arr[j + increment] = temp; 19 } 20 } 21 } 22 while (increment > 1) 23 return arr; 24 } 25 var ele = [4, 2, 1, 3, 7, 9, 6]; 26 console.log(shallSort(ele)); 27 </script>