分而治之算法设计中的一种方法,将一个问题分成多个和原问题相似的小问题,递归解决小问题,再将结果合并并解决原来的问题

归并排序

  • 分:把数组从中间一分为二
  • 解:递归对两个子数据进行归并排序
  • 合: 合并有序子数组

    1. /**
    2. * 归并排序
    3. */
    4. Array.prototype.mergeSort = function() {
    5. const rec = arr => {
    6. if (arr.length <= 1) {
    7. return arr;
    8. }
    9. const mid = Math.floor(arr.length / 2);
    10. const left = arr.slice(0, mid);
    11. const right = arr.slice(mid);
    12. const orderLeft = rec(left);
    13. const orderRight = rec(right);
    14. const res = [];
    15. while(orderLeft.length || orderRight.length) {
    16. if (orderLeft.length && orderRight.length) {
    17. res.push(orderLeft[0] > orderRight[0] ? orderRight.shift() : orderLeft.shift())
    18. } else if (orderLeft.length) {
    19. res.push(orderLeft.shift())
    20. } else if (orderRight.length) {
    21. res.push(orderRight.shift())
    22. }
    23. }
    24. return res;
    25. }
    26. const newArr = rec(this);
    27. newArr.forEach((item, index) => {
    28. this[index] = item;
    29. })
    30. }


    快速排序

  • 分:选基准,按基准把数组分成了两个子数组

  • 解:递归对两个子数组进行快速排序
  • 合:对两个子数组进行合并

    1. /**
    2. * 快速排序
    3. */
    4. Array.prototype.quickSort = function() {
    5. const rec = (arr) => {
    6. if (arr.length <= 1) {
    7. return arr;
    8. }
    9. const left = [];
    10. const right = [];
    11. const mid = arr[0];
    12. for (let i = 1; i < arr.length; i++) {
    13. if (arr[i] > mid) {
    14. right.push(arr[i])
    15. } else {
    16. left.push(arr[i])
    17. }
    18. }
    19. return [...rec(left), mid, ...rec(right)];
    20. }
    21. const newArr = rec(this);
    22. newArr.forEach((item, index) => {
    23. this[index] = item;
    24. })
    25. }