xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

使用 js 实现十大排序算法: 快速排序

QuickSort

快速排序

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description 快速排序 quicksort
 * @difficulty Medium
 * @complexity O(n*log(n))
 * @augments
 * @example
 * @link https://www.cnblogs.com/xgqfrms/p/13857663.html
 * @solutions
 *
 */

const log = console.log;

function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }
  // 中间 index
  let pivotIndex = Math.floor(arr.length / 2);
  // 截取中间值,✅ splice 改变原数组长度,  ❌ slice 不改变原数组长度
  const pivot = arr.splice(pivotIndex, 1)[0];
  const left = [];
  const right = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  // 递归
  return quickSort(left).concat([pivot], quickSort(right));
};


const arr = [12, 7, 5, 23, 18, 37, 1, 9, 17];

const test = quickSort(arr);

log(`arr =
`, arr)
log(`test =
`, test)

refs

js 十大排序算法 All In One

https://www.cnblogs.com/xgqfrms/p/13947122.html

https://www.cnblogs.com/xgqfrms/p/13857663.html



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


原文地址:https://www.cnblogs.com/xgqfrms/p/13947110.html