Js refactoring Array's sort sorting method

Source: Internet
Author: User

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/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.