快速排序思想
    取一个值最为基准,比它大的放右边小的放左边,对左右两边的数组递归或循环执行这步,直到所有子集只有一个元素(注意arr.length <= 1时 return)

    1. function quickSort (arr) {
    2. if (arr.length <= 1) {
    3. return arr;
    4. }
    5. let pivotIndex = Math.floor(arr.length / 2); // 取中间的脚标
    6. let pivot = arr.splice(pivotIndex, 1)[0]; // 通过脚标取出中间值
    7. let left = [];
    8. let right = [];
    9. for (let i = 0; i < arr.length; i++) {
    10. if (arr[i] < pivot) { // 比中间值小 放左边
    11. left.push(arr[i]);
    12. } else { // 大 右边
    13. right.push(arr[i]);
    14. }
    15. }
    16. let res = this.quickSort(left).concat([pivot], this.quickSort(right)); // 递归 拼接 中间值+左右数组
    17. return res;
    18. }
    19. // 换位的快速排序
    20. function quickSortTest (arr) {
    21. function patition (arr, start, end) {
    22. const pivot = arr[end];
    23. let index = start;
    24. for (let i = start; i < end; i++) {
    25. if (arr[i] < pivot) {
    26. [arr[i], arr[index]] = [arr[index], arr[i]];
    27. index++;
    28. }
    29. }
    30. [arr[index], arr[end]] = [arr[end], arr[index]];
    31. return index;
    32. }
    33. // 使用递归
    34. function quickSortR (arr, start, end) {
    35. if (start >= end) {
    36. return;
    37. }
    38. let index = patition(arr, start, end);
    39. quickSortR(arr, start, index - 1);
    40. quickSortR(arr, index + 1, end);
    41. }
    42. // 使用循环
    43. function quickSortI (arr) {
    44. let stack = [];
    45. stack.push(0);
    46. stack.push(arr.length - 1);
    47. while (stack[stack.length - 1] >=0) {
    48. let end = stack.pop();
    49. let start = stack.pop();
    50. let index = patition (arr, start, end);
    51. if (index - 1 > start) {
    52. stack.push(start);
    53. stack.push(index - 1);
    54. }
    55. if (index + 1 < end) {
    56. stack.push(index + 1);
    57. stack.push(end);
    58. }
    59. }
    60. }
    61. // quickSortI(arr);
    62. // quickSortR(arr, 0, arr.length - 1);
    63. }

    http://www.ruanyifeng.com/blog/2011/04/quicksort_in_javascript.html