使用递归。
使用扩展运算符 ( ...) 克隆原始数组arr。
如果数组的 length 小于2,则返回克隆的数组。
使用Math.floor()计算枢轴元素的索引。
使用Array.prototype.reduce() 和 Array.prototype.push()将数组拆分为两个子数组。第一个包含小于或等于pivot的元素,第二个包含大于它的元素。将结果分解为两个数组。
递归调用quickSort()创建的子数组。
const quickSort = arr => {
const a = [...arr];
if (a.length < 2) return a;
const pivotIndex = Math.floor(arr.length / 2);
const pivot = a[pivotIndex];
const [lo, hi] = a.reduce(
(acc, val, i) => {
if (val < pivot || (val === pivot && i != pivotIndex)) {
acc[0].push(val);
} else if (val > pivot) {
acc[1].push(val);
}
return acc;
},
[[], []]
);
return [...quickSort(lo), pivot, ...quickSort(hi)];
};
示例:
quickSort([1, 6, 1, 5, 3, 2, 1, 4]); // [1, 1, 1, 2, 3, 4, 5, 6]
更多内容请访问我的网站:https://www.icoderoad.com