The principle analysis of array sort method in js

  • 2020-03-30 04:21:23
  • OfStack

This paper analyzes the principle of array sort method in js with an example. Share with you for your reference. Specific analysis is as follows:

Recently, in the project of baidu, we need to sort the array. Of course, we naturally thought of the sort method of array at the beginning. The application of this method is very simple.

 window.onload=function(){
        var arr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98];
        var arr2=["George","John","Thomas","James","Adrew","Martin"];
        function arrsort(a,b){
            return a-b;
            }
        console.log(arr.sort(arrsort));  //Number sort requires a function, if you want to go from big to small, return b minus a; < br / >         console.log(arr2.sort());  //Letters do not need to be
}

But it occurred to me why sort is so simple and how it works. So I tried to sort the array without sort. The principle is to find the minimum value of the array and insert it into the new array, then delete the minimum value in the array, after updating the array, continue to look for the minimum value to insert, and so on. The code is as follows:
 window.onload=function(){
        var arr=[2,55,55,1,75,3,9,35,70,166,432,678,32,98];
        var len=arr.length;
        console.log(arr.join(","));
        var newarr=[];
        for(var i=0;i<len;i++){
            newarr.push(Math.min.apply(null,arr));  //Insert the minimum into the new array
            arr.splice(r(arr,Math.min.apply(null,arr)),1);  //Immediately after insertion, delete the minimum
        }
        //Find the position of the minimum in the array
        function r(s,v){
            for(k in s){
                if(s[k] == v){
                    return k;
                    }
                }
            }
        console.log(newarr.join(","))
}

PS: this is just a method I wrote, the principle of sort should not be like this, you can also use bubble method to sort the array, I will not write the code, a lot of the Internet.


Related articles: