快速排序

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /*
            3.快速排序
            排序思路: 1.取出【删除】数组中间项
                       2.将删减后的新数组与 刚取出来的中间项逐个进行比较
                       3.设置两个空数组,若比中间项小,则放入一个空数组中,若比中间项大,则放入另一个空数组中。
                       4.反复比较,数组拼接
        */
        var arr = [22, 5, 3, 16, 34, 61, 7];
        var arr2 = [30,6,12,55,47,9,8];

        function quickSort(a) {   // a 形参
            // 对要排序的数组进行长度判断,如果数组内只剩下一个数字了,就不需要折半比较了
            if(a.length <=1){
                return a;
            }
            var one = a.splice(Math.floor(a.length / 2), 1)[0];  // 中间值

            var left = [];
            var right = [];
            for (var i = 0; i < a.length; i++) {
                if (a[i] < one) {  // 比中间值小的数字 添加到left数组中
                    left.push(a[i]);
                } else {
                    right.push(a[i]);
                }
            }
        
            return quickSort(left).concat(one, quickSort(right));  // 递归 反复调用自己的函数
       
        }
        
        console.log(quickSort(arr2));
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/shihaiying/p/13230232.html