归并排序(Divide && Conquer)

  1. function mergeSort(arr) {
  2. const len = arr.length
  3. if (len < 2) return arr
  4. // 取中位索引,分割左数组和右数组
  5. let middle = Math.floor(len / 2),
  6. left = arr.slice(0, middle),
  7. right = arr.slice(middle)
  8. return merge(mergeSort(left), mergeSort(right))
  9. }
  10. function merge(left, right) {
  11. const ans = []
  12. while(left.length && right.length) {
  13. if (left[0] <= right[0]) {
  14. ans.push(left.shift())
  15. } else {
  16. ans.push(right.shift())
  17. }
  18. }
  19. while(left.length) ans.push(left.shift())
  20. while(right.length) ans.push(right.shift())
  21. return ans
  22. }

快速排序

  1. function quickSort(arr) {
  2. if (arr.length <=1) return arr
  3. const pivot = Math.floor(arr.length / 2)
  4. const left = [],
  5. right = []
  6. }

堆排序