数组快速排序

举个栗子:

对下面数组进行排序:

let originArray = [[45, 26, 78, [77, 23], 66], 24, 63,63, [45, 10], 17, 31, 96, 50];

分治法;

function quickSort(arr){
        arr = arr.join(",").split(",").map(Number);
        var recursion = function(targetArray){
            let baseIndex = Math.floor(targetArray.length/2),
                miduleNumer,
                leftArray = [],
                miduleArray = [],
                rightArray = [];
            if(targetArray.length <= 1) return targetArray;
            miduleNumer = targetArray.splice(baseIndex,1)[0];
            for(let i = 0;i < targetArray.length;i++){
                if(targetArray[i] > miduleNumer){
                    leftArray.push(targetArray[i]);
                }else if(targetArray[i] < miduleNumer){
                    rightArray.push(targetArray[i]);
                }else{
                    miduleArray.push(targetArray[i]);
                }
            } 
            return [...recursion(leftArray),...recursion(miduleArray),...recursion([miduleNumer]),...recursion(rightArray)];
        }
        return recursion(arr);
    }

二:

function quickSort(arr){
         arr = arr.join(",").split(",").map(Number);
         let resultArr = [];
         function recursion(targetArr){
           if(targetArr.length > 0){
            let minNum = Math.min(...targetArr);
            targetArr.splice(targetArr.indexOf(minNum),1);
          resultArr.unshift(minNum);
            recursion(targetArr);
          }
        }
        recursion(arr);
        return resultArr;
     }
     console.log(quickSort(targetArray));

 

.

posted @ 2021-08-09 23:17  古墩古墩  Views(108)  Comments(0Edit  收藏  举报