【发布时间】: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.
我必须完全理解代码的工作原理,但是,在您看来,我所说的是否正确?
谢谢
【问题讨论】:
-
这基本上是Lomuto partition scheme。与避免不必要的交换相比,检查 splitIndex != i 可能需要更多时间。
标签: javascript arrays quicksort