标签:间隔 cat 排序算法 const 索引 sele temp function 选择排序
1、冒泡排序
let arr =[9,8,11,1,30] function bubble_sort(arr){ let swap for(let i=0;i<arr.length-1;i++){ for(let j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ swap=arr[j] arr[j]=arr[j+1] arr[j+1]=swap } } } } bubble_sort(arr) console.log(arr) //[1, 8, 9, 11, 30]
2、快速排序
let arr =[9,8,11,1,30] function quick_sort(arr){ if(arr.length<=1){ return arr; } const pivotIndex=Math.floor(arr.length/2); const pivot=arr.splice(pivotIndex,1)[0]; const left=[]; const right=[]; for(let i=0;i<arr.length;i++){ if(arr[i]<pivot){ left.push(arr[i]); }else{ right.push(arr[i]); } } return quick_sort(left).concat([pivot],quick_sort(right)); } console.log(quick_sort(arr)) //[1, 8, 9, 11, 30] console.log(arr) //[9, 8, 1, 30]
3、选择排序
let arr =[9,8,11,1,30] function selection_sort(arr) { var len = arr.length; var minIndex, swap; for (let i = 0; i < len - 1; i++) { minIndex = i; for (let j = i + 1; j < len; j++) { if (arr[j] < arr[minIndex]) { //寻找最小的数 minIndex = j; //将最小数的索引保存 } } swap = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = swap; } return arr; } console.log(selection_sort(arr)) //[1, 8, 9, 11, 30] console.log(arr) //[1, 8, 9, 11, 30]
4、插入排序
let arr =[9,8,11,1,30] function insertion_sort(arr) { for (var i = 1; i < arr.length; i++) { var key = arr[i]; var j = i - 1; while ( arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } return arr; } console.log(insertion_sort(arr)) //[1, 8, 9, 11, 30] console.log(arr) //[1, 8, 9, 11, 30]
5、希尔排序
let arr =[9,8,11,1,30] function shell_sort(arr) { var len = arr.length, temp, gap = 1; while(gap < len/5) { //动态定义间隔序列 gap =gap*5+1; } for (gap; gap > 0; gap = Math.floor(gap/5)) { for (var i = gap; i < len; i++) { temp = arr[i]; for (var j = i-gap; j >= 0 && arr[j] > temp; j-=gap) { arr[j+gap] = arr[j]; } arr[j+gap] = temp; } } return arr; } console.log(shell_sort(arr)) //[1, 8, 9, 11, 30] console.log(arr) //[1, 8, 9, 11, 30]
标签:间隔 cat 排序算法 const 索引 sele temp function 选择排序
原文地址:https://www.cnblogs.com/huangqiming/p/10412723.html