Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

快速排序 #195

Open
Sunny-117 opened this issue Nov 3, 2022 · 4 comments
Open

快速排序 #195

Sunny-117 opened this issue Nov 3, 2022 · 4 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Achetto
Copy link

Achetto commented Dec 2, 2022

Array.prototype.quickSort = function () {
  const rec = (arr) => {
    if (arr.length < 2) { return arr; }
    const left = [];
    const right = [];
    const mid = arr[0];
    for (let i = 1; i < arr.length; i++) {
      if (arr[i] < mid) {
        left.push(arr[i]);
      } else {
        right.push(arr[i]);
      }
    }
    return [...rec(left), mid, ...rec(right)];
  };

  const res = rec(this);
  // 把arr里面的值改为res
  res.forEach((n, i) => {
    this[i] = n;
  })
}
// 递归时间复杂度O(logN),分区时间复杂度O(n),总体时间复杂度为O(nlogN);
const arr = [6,5,4,3,2,1];
arr.quickSort();

@xiaodye
Copy link

xiaodye commented Jan 11, 2023

需额外空间,非原地排序

/**
 * 快速排序
 * @param arr 待排序数组
 * @returns
 */
const quickSort = function (arr: number[]): number[] {
  if (arr.length <= 1) {
    return arr;
  }

  const pivotIndex = Math.floor(arr.length / 2);
  // 从数组中取出我们的"基准"元素
  const pivot = arr.splice(pivotIndex, 1)[0];
  const leftArr: number[] = [];
  const rightArr: number[] = [];

  for (let i = 0; i < arr.length; i++) {
    if (arr[i] <= pivot) {
      leftArr.push(arr[i]);
    } else {
      rightArr.push(arr[i]);
    }
  }

  // 至此,我们将数组分成了left和right两个部分,中间的一个元素pivot之前被删了,现在要加回来
  return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
};

// test
const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(quickSort(arr));

@bearki99
Copy link

function quick_sort(q, l, r) {
  if (l >= r) return;
  let i = l - 1,
    j = r + 1,
    x = q[(i + j) >> 1];
  while (i < j) {
    do i++;
    while (q[i] < x);
    do j--;
    while (q[j] > x);
    if (i < j) {
      [q[i], q[j]] = [q[j], q[i]];
    }
  }
  quick_sort(q, l, j), quick_sort(q, j + 1, r);
}
const num = [3, 4, 2, 1, 6, 7, 4];
quick_sort(num, 0, num.length - 1);
console.log(num);

@zhuba-Ahhh
Copy link
Contributor

function quickSort(arr) {
  if (arr.length < 2) return arr;
  const left = [],
    right = [],
    cur = arr.splice(0, 1);
  for (let item of arr)
    item > cur ? right.push(item) : left.push(item);
  return quickSort(left).concat(cur, quickSort(right));
}

const arr = [98, 42, 25, 54, 15, 3, 25, 72, 41, 10, 121];
console.log(quickSort(arr));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants