This sorting is for comparison.
Sort the array in descending order var a = [3, 1, 5, 6, 4, 2];
The first round of comparison: Compare the first value with other elements in the current array.
3 to 1
3 is bigger than 5 // 5, so the exchange is a = [5, 1, 3, 6, 4, 2];
5 to 6 // exchange a = [6, 1, 3, 5, 4, 2];
6 to 4
6 to 2
The final result of the first round is a = [6, 1, 3, 5, 4, 2];
The second round of comparison: Compare the second value with the element after this value
1 to 3 // exchange a = [6, 3, 1, 5, 4, 2];
3 to 5 // exchange a = [6, 5, 1, 3, 4, 2];
5 to 4
5 to 2
The second round of final result a = [6, 5, 1, 3, 4, 2];
In this way, exchange data in sequence.
The third round of final result a = [6, 5, 4, 1, 3, 2];
The fourth round of final result a = [6, 5, 4, 3, 1, 2];
The final result of the fifth round is a = [6, 5, 4, 3, 2, 1].
The following is a refactoring method:
Copy codeThe Code is as follows: Array. prototype. fst = function (fn ){
Var fn = fn | function (a, B) {return a> B ;};
For (var I = 0; I <this. length; I ++ ){
For (var j = I; j <this. length; j ++ ){
If (fn (this [I], this [j])> 0 ){
Var t = this [I];
This [I] = this [j];
This [j] = t;
}
}
}
Return this;
};
View the demo<Meta charset = "UTF-8"> <meta name = "auther" content = "F7"> <br/> check the source code. The source code is clearer! <Br/>