快速排序算法 - JavaScript。我被卡住了:(

问题描述 投票:0回答:1

有人能告诉我为什么这会产生无限循环吗?我被困住了。 也许我错过了什么?

const quickSort = function (arr) {
  if (arr.length < 2) {
    return arr;
  }
  const pivot = arr[0];
  const smallerThanPivot = [];
  const highterThanPivot = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      smallerThanPivot.push(arr[i]);
    } else {
      highterThanPivot.push(arr[i]);
    }
  }
  return [
    ...quickSort(smallerThanPivot),
    pivot,
    ...quickSort(highterThanPivot),
  ];
};
javascript infinite-loop quicksort
1个回答
0
投票

您不会从数组中删除

pivot
,这会导致
[1, 2, 3]
被分成
[], [1, 2, 3]
,因为枢轴被放置到更高的部分

© www.soinside.com 2019 - 2024. All rights reserved.