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

快排算法实现 #5

Closed
jerryyxu opened this issue Sep 11, 2021 · 1 comment
Closed

快排算法实现 #5

jerryyxu opened this issue Sep 11, 2021 · 1 comment
Assignees
Labels
基础 编程基础 小记 知识点,记得经常看看
Milestone

Comments

@jerryyxu
Copy link
Owner

jerryyxu commented Sep 11, 2021

排序思路(从小到大):

  • 选择一个基准数(pivot),进行排序,分区(partition)
  • 让基准数左边分区的数都小于基准数,右分区的数值都大于基准数,获得该基准数索引
  • 对基准数左右分区进行重复上述步骤进行排序,直到分区长度小于 1
function quickSort(arr) {
  return partition2(arr, 0, arr.length);
}

function partition(arr, low, high) {
  const pivot = low;
  let index = pivot + 1;

  for (let i = index; i <= high; i++) {
    if (arr[i] < arr[pivot]) {
      swap(arr, i, index);
      index++;
    }
  }

  index--;
  swap(arr, pivot, index);

  return index;
}

function swap(arr, i, j) {
  i !== j && ([arr[i], arr[j]] = [arr[j], arr[i]]);
}

function partition2(arr, low, high) {
  if (low < high) {
    const pivot = partition(arr, low, high);

    partition2(arr, low, pivot - 1);
    partition2(arr, pivot + 1, high);
  }

  return arr;
}
@jerryyxu jerryyxu added 小记 知识点,记得经常看看 基础 编程基础 labels Sep 11, 2021
@jerryyxu jerryyxu added this to the 2021-09 milestone Sep 11, 2021
@jerryyxu jerryyxu self-assigned this Sep 11, 2021
@jerryyxu
Copy link
Owner Author

快速排序是不稳定的排序算法,平均时间复杂度为 O(nlogn) ,最好情况下为 O(nlogn),最差情况下为 O(n^2)。另外,快速排序算法实现上还是递归的方式,在无法实现尾递归优化的情况下还是存在调用栈溢出的可能,因此不能进行大量数据的排序。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
基础 编程基础 小记 知识点,记得经常看看
Projects
None yet
Development

No branches or pull requests

1 participant