The principle of array sort method in JS is analyzed in this paper. Share to everyone for your reference. The specific analysis is as follows:
Recently in Baidu's project to use the array to sort, of course, the first natural thought of the array of the sort method, this method is very simple application, roughly as follows:
Copy Code code as follows:
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)); The number order needs function, if want from big row to small, return b-a;
Console.log (Arr2.sort ()); Letters don't need
}
But it occurred to me, why is the sort usage so simple, and what is the principle? So I tried not to sort the array by finding the minimum value of the arrays to insert into the new array, and then deleting the smallest value in the array, updating the array, and continuing to look for the minimum insertion, so that the code is as follows:
Copy Code code 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)); Inserts the minimum value into the new array
Arr.splice (R (arr,math.min.apply (Null,arr)), 1); Delete the minimum value immediately after inserting
}
Find the location of the smallest value 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 sort principle should not be like this, you can also use bubble to sort the array, the code I do not write, online a lot of. Of course, the above code just sorts the array of numbers, and for the sort of strings, you can consider the Localecompare method of the string.
I hope this article will help you with your JavaScript programming.