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 to apply, roughly as follows:
code is as follows |
copy code |
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)); //numeric sorting requires a function, if you want to from the big row to the small, return B-a; Console.log (Arr2.sort ()); //Letters not required |
But it suddenly occurred to me, why is the sort usage so simple, and what exactly 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:
The code is as follows |
Copy Code |
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.