【问题标题】:Quick Sort in jsjs中的快速排序
【发布时间】:2019-04-09 13:46:23
【问题描述】:

我在 medium 上找到了这个 article,我正试图弄清楚代码的实际作用。

这是代码:

帮手

const defaultComparator = (a, b) => {
  if (a < b) {
    return -1;
  }
  if (a > b) {
    return 1;
  }
  return 0;
};

排序功能

const quickSort = (
  unsortedArray,
  comparator = defaultComparator
) => {

  // Create a sortable array to return.
  const sortedArray = [ ...unsortedArray ];

  // Recursively sort sub-arrays.
  const recursiveSort = (start, end) => {

    // If this sub-array is empty, it's sorted.
    if (end - start < 1) {
      return;
    }

    const pivotValue = sortedArray[end];
    let splitIndex = start;
    for (let i = start; i < end; i++) {
      const sort = comparator(sortedArray[i], pivotValue);

      // This value is less than the pivot value.
      if (sort === -1) {

        // If the element just to the right of the split index,
        //   isn't this element, swap them.
        if (splitIndex !== i) {
          const temp = sortedArray[splitIndex];
          sortedArray[splitIndex] = sortedArray[i];
          sortedArray[i] = temp;
        }

        // Move the split index to the right by one,
        //   denoting an increase in the less-than sub-array size.
        splitIndex++;
      }

      // Leave values that are greater than or equal to
      //   the pivot value where they are.
    }

    // Move the pivot value to between the split.
    sortedArray[end] = sortedArray[splitIndex];
    sortedArray[splitIndex] = pivotValue;

    // Recursively sort the less-than and greater-than arrays.
    recursiveSort(start, splitIndex - 1);
    recursiveSort(splitIndex + 1, end);
  };

  // Sort the entire array.
  recursiveSort(0, unsortedArray.length - 1);
  return sortedArray;
};

所以,我花了一段时间弄清楚splitIndex 的工作原理。它从 0 开始,只有当 for 循环中的当前元素小于枢轴时,它才会增加 1。当我们遇到一个大于枢轴值的数字时,splitIndex 保持在它的值,i 增加。在下一步中,如果数字也小于枢轴,我们交换它们

例如对于这个数组:[2,4,65,1,15] splitIndex 和 i 相等,在 for 循环期间,直到我们得到数字 65。这里 splitIndex 不增加,当我们到达数字 1 时,我们交换 1 和 65 .

我不是英语母语者,所以我完全不明白作者的意思:

 // If the element just to the right of the split index,
        //   isn't this element, swap them.

我必须完全理解代码的工作原理,但是,在您看来,我所说的是否正确?

谢谢

【问题讨论】:

标签: javascript arrays quicksort


【解决方案1】:

splitIndex 变量跟踪(在您当前正在排序的数组部分中)比枢轴“更小”和“等于或大于”的元素之间的分隔线。您对其工作原理的描述似乎基本正确。

一般情况下,如果遇到小于主元的元素,我们会将其与splitIndex 处的元素交换,将其放入“小于主元”部分,然后递增splitIndex 表示该部分已经成长。如果我们遇到一个相等或更大的,我们将它留在原处,并且不增长该部分。

这是有道理的假设splitIndex 处的元素不小于枢轴。如果i 大于splitIndex 则为真,因为那时我们已经遇到了至少一个这样的元素,并跳过了它。

例外情况是,如果我们当前检查splitIndex 处的元素(只要到目前为止所有元素都小于枢轴)。在这种情况下,我们将与自身交换元素。这是多余的,所以这就是splitIndex !== i 检查的原因。

至于

    // If the element just to the right of the split index,
    //   isn't this element, swap them.

我怀疑作者在评论中犯了一个错误。它应该说“分割索引处的元素”,而不是“分割索引右侧的元素”。

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 2014-10-10
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多