Published on

归并排序笔记以及实现

Authors
  • avatar
    Name
    Et cetera
    Twitter

基本思想

  • 将待排序数组分成若干个子数组

  • 然后将相邻的子数组并成一个有序数组

  • 最后将这些有序数据归并成一个整体、有序的数组

mergeSort.ts
function mergeSort(arr: number[]): number[] {
  if (arr.length <= 1) return arr;

  const mid = Math.floor(arr.length / 2);
  const left = arr.slice(0, mid);
  const right = arr.slice(mid);

  const newLeft = mergeSort(left);
  const newRight = mergeSort(right);

  let i = 0;
  let j = 0;
  const newArr: number[] = [];
  while (i < newLeft.length && j < newRight.length) {
    if (newLeft[i] < newRight[j]) {
      newArr.push(newLeft[i]);
      i++;
    } else {
      newArr.push(newRight[j]);
      j++;
    }
  }

  if (i < newLeft.length) {
    newArr.push(...newLeft.slice(i));
  }
  if (j < newRight.length) {
    newArr.push(...newRight.slice(j));
  }

  return newArr;
}

时间复杂度

  • 最好情况:O(logn)

  • 最坏情况:O(nlogn)