升序排列数组

  1. function merge(left, right) {
  2. const res = [];
  3. while (left.length && right.length) {
  4. left[0] <= right[0] ? res.push(left.shift()) : res.push(right.shift());
  5. }
  6. return res.concat(left, right);
  7. }
  8. function mergeSort(arr) {
  9. if (arr.length < 2) {
  10. return arr;
  11. }
  12. const mid = Math.floor(arr.length / 2);
  13. const left = arr.slice(0, mid);
  14. const right = arr.slice(mid);
  15. return merge(mergeSort(left), mergeSort(right));
  16. }

算法测试

  1. console.log(mergeSort([5, 4, 6, 3, 35, 17, 1]));
  2. // [ 1, 3, 4, 5, 6, 17, 35 ]
  3. console.log(mergeSort([12, 1, 5, 5, 7, 78]));
  4. // [ 1, 5, 5, 7, 12, 78 ]
  5. console.log(mergeSort([-3, 7, -8, 4, 6, -5, -4, 5]));
  6. // [ -8, -5, -4, -3, 4, 5, 6, 7 ]