碎片时间学编程「69]:使用快速排序算法对数字数组进行排序

使用递归。

使用扩展运算符 ( ...) 克隆原始数组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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容