代码如下:
1、冒泡排序
1 <script> 2 var arr = [9, 8, 7, 5, 7, 1, 45, 12, 7, 74, 4]; 3 for (var i = 0; i < arr.length; i++) { 4 for (var j = 0; j < arr.length - i - 1; j++) { 5 if (arr[j] > arr[j + 1]) { 6 var temp=arr[j]; 7 arr[j]=arr[j+1]; 8 arr[j+1]=temp; 9 } 10 } 11 } 12 console.log(arr); 13 </script>
2、选择排序
1 <script> 2 var arr = [9, 8, 7, 5, 7, 1, 45, 12, 7, 74, 4]; 3 for (var i = 0; i < arr.length - 1; i++) { 4 for (var j = i + 1; j < arr.length; j++) { 5 if (arr[i] > arr[j]) { 6 var temp = arr[j]; 7 arr[j] = arr[i]; 8 arr[i] = temp; 9 } 10 } 11 } 12 console.log(arr); 13 </script>
3、快速排序
1 <script> 2 var arr = [9, 8, 7, 5, 7, 1, 45, 12, 7, 74, 4]; 3 4 function quickSort(arr) { 5 // 递归停止条件 6 if (arr.length <= 1) { 7 return arr; 8 } 9 var midIndex = parseInt(arr.length / 2); 10 var left = []; 11 var right = []; 12 arr.forEach(function (item, index) { 13 if (index == midIndex) { 14 15 } else if (arr[index] < arr[midIndex]) { 16 left.push(arr[index]); 17 } else { 18 right.push(arr[index]); 19 } 20 }); 21 return quickSort(left).concat(arr[midIndex]).concat(quickSort(right)); 22 } 23 console.log(quickSort(arr)); 24 </script>
4、插入排序
<script> var arr = [9, 8, 7, 5, 7, 1, 45, 12, 7, 74, 4]; for (var i = 0; i < arr.length; i++) { var m=i; while (i - 1 >= 0 && arr[m] < arr[m - 1]) { var temp=arr[m]; arr[m]=arr[m-1]; arr[m-1]=temp; m--; } } console.log(arr); </script>
5、希尔排序
1 <script> 2 var arr = [9, 8, 7, 5, 7, 1, 45, 12, 7, 74, 4]; 3 //设定步长初始值 4 var interval = parseInt(arr.length / 2); 5 while (interval > 0) { 6 for (var i = 0; i < arr.length; i++) { 7 var m = i; 8 while (i - 1 >= 0 && arr[m] < arr[m - interval]) { 9 var temp = arr[m]; 10 arr[m] = arr[m - interval]; 11 arr[m - interval] = temp; 12 m--; 13 } 14 } 15 interval = parseInt(interval / 2); 16 } 17 console.log(arr); 18 </script>