思路

(1)从数组中选择一个值作为主元,

(2)进行划分操作,使得
比主元小的值都排在主元之前
比主元大的值都排在主元之后,

(3)对划分后的小数组重复之前的两个步骤,直至数组完全排序

实现

quickSort

  1. function quickSort(array) {
  2. return quick(array, 0, array.length - 1);
  3. }

quick

  1. function quick(array, left, right) {
  2. let index;
  3. if (array.length > 1) {
  4. index = partition(array, left, right);
  5. if (left < index - 1) { // 存在左子数组
  6. quick(array, left, index - 1);
  7. }
  8. if (index < right) { // 存在右子数组
  9. quick(array, index, right);
  10. }
  11. }
  12. return array;
  13. }

partition

  1. function partition(array, left, right) {
  2. const index = Math.floor(Math.random() * (right - left + 1) + left),
  3. pivot = array[index];
  4. let i = left,
  5. j = right;
  6. while (i <= j) {
  7. while (array[i] <= pivot) {
  8. i++;
  9. }
  10. while (array[i] >= pivot) {
  11. j--;
  12. }
  13. if (i <= j) {
  14. [array[i], array[j]] = [array[j], array[i]];
  15. i++;
  16. j--;
  17. }
  18. }
  19. return i;
  20. }