1, JS Sort () Method of application:
First: If the method is called without parameters, the elements in the array are sorted alphabetically, more precisely, by the order in which the characters are encoded. To do this, you should first convert the elements of the array to a string, if necessary, for comparison.
If you want to sort by other criteria, you need to provide a comparison function that compares two values and returns a number that describes the relative order of the two values. The comparison function should have two parameters A and B with the following return values:
- If a is less than B, a value that is less than 0 is returned if a should appear before B in the sorted array.
- If a equals B, 0 is returned.
- If a is greater than B, a value greater than 0 is returned.
(from the Consortium);
However: The emphasis came however!!!
Example 1:
<script> varnew Array (12,23,1,4,23,34,2,5); Numarr.sort (function Compare (b) {return a-b;}) ; for (var i = 0; i<numarr.length; i++) { + "<br>"); } </script>
This section of code shows the result: positive order! 1, 2,4,5,12,23,23,34
Example two:
<script> varnew Array (12,23,1,4,23,34,2,5); Numarr.sort (function Compare (A, b) {return B-A; }); for (var i = 0; i<numarr.length; i++) { + "<br>"); }
This section of code shows the result: Reverse! 34,23,23,12,5,4,2,1
This indicates that the result of the positive sequence reverse is related to the position of the parameter in the sort () method function.
Principle of the 2js sort () method:
Bubble Sort method.
Cases:
var ArrA = [6,2,4,3,5,1]; Arra.sort ();
This sort is done in 22 comparisons.
Like you, this array is sorted in ascending order var ArrA = [6,2,4,3,5,1];
Compare 6,2 for the first time
6:2 Big Get 2,6
The original array becomes [2,6,4,3,5,1]
The 2nd time compares 2nd and 3rd numbers, 6 and 4.
6:4 big, get 4,6
Results [2,4,6,3,5,1]
The 3rd time compares 3rd and 4th numbers 6 and 3.
Get [2,4,3,6,5,1]
4th time [2,4,3,5,6,1]
5th time [2,4,3,5,1,6]
The first round is complete
Second round
6th time, 2:4 small, unchanged [2,4,3,5,1,6]
7th time [2,3,4,5,1,6]
8th Time 4:5 Small, unchanged [2,3,4,5,1,6]
9th time [2,3,4,1,5,6]
Third round
10th time 2:3 Small, unchanged [2,3,4,1,5,6]
11th time 3:4 Small, unchanged [2,3,4,1,5,6]
12th time [2,3,1,4,5,6]
4th round
13th time 2:3 Small, unchanged [2,3,1,4,5,6]
14th time [2,1,3,4,5,6]
15th time [1,2,3,4,5,5]
Follow the process in the same way.
3, random arrangement of the wording
Arr.sort (function () {return math.random () <0.5?1:-1;});
The principle and application of sort sorting for JS array