再帰関数:

意味:自分自身を調整する

再帰の 3 つの要素: 関数の定義、終了条件、等価関係

小物ケース:仕分け

        let arr1 = [8, 8, 9, 13, 45, 8, 0, 1, 9, 66];
        
        //定义函数
        function quickSort(arr) {
            //终止条件
            if (arr.length <= 1) return arr;

            const baseIndex = Math.floor(arr.length / 2);
            console.log(baseIndex);
            const baseVal = arr.splice(baseIndex, 1)[0];
            console.log(baseVal);

            const left = [];
            const right = [];

            for (let i = 0; i < arr.length; i++) {
                if (arr[i] < baseVal) {
                    left.push(arr[i]);
                } else {
                    right.push(arr[i])
                }


            }
            
            //等价关系式    
            return quickSort(left).concat(baseVal, quickSort(right));

        }

        console.log(quickSort(arr1));

 

おすすめ

転載: blog.csdn.net/weixin_48123820/article/details/131500125