Today, I will introduce you to the principle of an array sorting sort method in js. I hope this method will be helpful to you.
Recently, Baidu projects used to sort arrays. Of course, at the beginning, we naturally thought of the array sort method. This method is very simple to use, roughly as follows:
The Code is as follows: |
Copy code |
Window. onload = function (){ Var arr = [70,166,432,678,]; Var arr2 = ["George", "John", "Thomas", "James", "Adrew", "Martin"]; Function arrsort (a, B ){ Return a-B; } Console. log (arr. sort (arrsort); // a function is required for sorting numbers. To sort numbers from large to small, return B-; Console. log (arr2.sort (); // The letter is not required
|
} But I suddenly thought, why is the sort usage so simple? What is its principle? So I try not to use sort to sort the array. 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, I continue to find the minimum value and insert it, the Code is as follows:
The Code is as follows: |
Copy code |
Window. onload = function (){ Var arr = [70,166,432,678,]; 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 value into the new array. Arr. splice (r (arr, Math. min. apply (null, arr), 1); // after inserting, immediately delete the minimum value } // Locate the position of the minimum 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 have written. The sort principle should not be like this. You can also sort the array by using the bubble method. I will not write the code. There are a lot of code on the Internet. of course, the above Code only sorts the number array. For string sorting, you can consider the localeCompare method of the string.