1. const quickSort = arr => {
    2. if (arr.length <= 1) {
    3. return arr;
    4. }
    5. //取基准点
    6. const midIndex = Math.floor(arr.length / 2);
    7. //取基准点的值,splice(index,1) 则返回的是含有被删除的元素的数组。
    8. const valArr = arr.splice(midIndex, 1);
    9. const midIndexVal = valArr[0];
    10. const left = []; //存放比基准点小的数组
    11. const right = []; //存放比基准点大的数组
    12. //遍历数组,进行判断分配
    13. for (let i = 0; i < arr.length; i++) {
    14. if (arr[i] < midIndexVal) {
    15. left.push(arr[i]); //比基准点小的放在左边数组
    16. } else {
    17. right.push(arr[i]); //比基准点大的放在右边数组
    18. }
    19. }
    20. //递归执行以上操作,对左右两个数组进行操作,直到数组长度为 <= 1
    21. return quickSort(left).concat(midIndexVal, quickSort(right));
    22. };
    1. // 快速排序
    2. const quickSort = (arr, left, right) => {
    3. let len = arr.length,
    4. partitionIndex;
    5. left = typeof left != 'number' ? 0 : left;
    6. right = typeof right != 'number' ? len - 1 : right;
    7. if (left < right) {
    8. partitionIndex = partition(arr, left, right);
    9. quickSort(arr, left, partitionIndex - 1);
    10. quickSort(arr, partitionIndex + 1, right);
    11. }
    12. return arr;
    13. };
    14. const partition = (arr, left, right) => {
    15. //分区操作
    16. let pivot = left, //设定基准值(pivot)
    17. index = pivot + 1;
    18. for (let i = index; i <= right; i++) {
    19. if (arr[i] < arr[pivot]) {
    20. swap(arr, i, index);
    21. index++;
    22. }
    23. }
    24. swap(arr, pivot, index - 1);
    25. return index - 1;
    26. };
    27. const swap = (arr, i, j) => {
    28. let temp = arr[i];
    29. arr[i] = arr[j];
    30. arr[j] = temp;
    31. };