function shuffle(arr) { let len = arr.length let temp for(let i = len-1; i>=0; i--) { let index = Math.floor(Math.random() * len); temp = arr[i] arr[i] = arr[index] arr[index] = temp } return arr }
function bubbleSort(arr) { let temp for (i = 0; i < arr.length - 1; i++) { for (j = 0; j< arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } return arr }
bubbleSort([6, 5, 4, 3, 2, 1])
2. 快速排序找基准,左右递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
function quickSort(arr) { let len = arr.length; if (len <=1 ) return arr; let pivotIndex = Math.floor(len / 2) let pivot = arr.splice(pivotIndex, 1)[0] let left = [] let right = [] arr.forEach(num => { if (num < pivot) { left.push(num) } else { right.push(num) } }) return quickSort(left).concat([pivot],quickSort(right)); } let newArr = quickSort([4, 2, 9, 7, 3]) console.log(newArr)