JS array quick sort

1. Find the middle subscript mIndex of the array. Because it may not be an integer, use Math.floor() to round down.
2. Get the value mVal of the middle subscript in the array through the middle subscript.
3. Create two empty arrays on the left and right. Values ​​less than mVal are placed in the left array, and values ​​greater than mVal are placed in the right array.
4. Use function recursion to fill the left and right arrays in turn.
5. Use the concat method to concatenate and return the new array.

       var arr = [4,56,12,435,32,7,8,90,1,2,3,54,56];

        function qSort(arr){
    
    
        	//如果数组长度是1,直接return,不需要排序
            if(arr.length <= 1) return arr;
            var mIndex = Math.floor(arr.length - 1 / 2);
            var mVal = arr.splice(mIndex,1);
            var lArr = [], rArr=[];
            for(var i = 0; i< arr.length ; i++){
    
    
                if(arr[i] < mVal){
    
    
                    lArr.push(arr[i]);
                }else{
    
    
                    rArr.push(arr[i]);
                }
            }
            return qSort(lArr).concat(mVal,qSort(rArr));
        }
        console.log(qSort(arr)); 

Insert picture description here

Guess you like

Origin blog.csdn.net/YL971129/article/details/113837105