归纳公式

快速排序 - 图1
**

转公式为代码

  1. const quickSort = (a) => {
  2. const [pivot, ...rest] = a;
  3. return (a.length <= 1)
  4. ? a
  5. : [
  6. ...quickSort(rest.filter((i) => i <= pivot)),
  7. pivot,
  8. ...quickSort(rest.filter((i) => i > pivot))
  9. ]
  10. }

优化:减少遍历(一次遍历多做事),减少复制(就地操作)
https://jsbin.com/fuvacosaxe/1/edit?js,console
https://jsbin.com/fuvacosaxe/2/edit?js,console

  1. const swap = (a, i, j) => [a[i], a[j]] = [a[j], a[i]];
  2. const handlePivot = (a, start, end) => {
  3. if (end - start === 0) return -1;
  4. if (end - start === 1) return 0;
  5. const pivot = a[start];
  6. let smallEnd = start, bigStart = end, i = start + 1;
  7. while(bigStart - smallEnd > 1) {
  8. console.log(`smallEnd ${smallEnd} bigStart ${bigStart}`)
  9. console.log(`${a[i]}, pivot ${pivot} i ${i}`)
  10. if(a[i] > pivot) {
  11. bigStart -= 1;
  12. swap(a, i, bigStart)
  13. } else {
  14. smallEnd += 1;
  15. swap(a, i, smallEnd);
  16. i += 1;
  17. }
  18. }
  19. console.log(a)
  20. swap(a, start, smallEnd)
  21. console.log(a)
  22. return smallEnd;
  23. }
  24. const quickSort = (a) => quickSortArray(a, 0, a.length);
  25. const quickSortArray = (a, start, end) => {
  26. if (end - start <= 1) return a;
  27. const pivotIndex = handlePivot(a, start, end);
  28. quickSortArray(a, start, pivotIndex);
  29. quickSortArray(a, pivotIndex + 1, end);
  30. return a;
  31. }
  32. console.log('------------', quickSort([2, 1, 3, 1, 4]))