Home > Web Front-end > JS Tutorial > js Reconstruct Array's sort sorting method_javascript skills

js Reconstruct Array's sort sorting method_javascript skills

WBOY
Release: 2016-05-16 18:04:45
Original
1425 people have browsed it

This sorting is a pairwise comparison.
Take this array and sort it in descending order var a = [3, 1, 5, 6, 4, 2];
First round of comparison: compare the first value with other elements of this array
3 to 1
3 to 5 //5 is larger, so the exchange results in a = [5, 1, 3, 6, 4, 2];
5 to 6 //The exchange results in a = [6 , 1, 3, 5, 4, 2];
6 to 4
6 to 2
The final result of the first round a = [6, 1, 3, 5, 4, 2];
Second round of comparison: Compare the second value with the elements after this value
1 to 3 //Exchange to get 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 final result of the second round is a = [6, 5, 1, 3, 4, 2];
Exchange in this way
The final result of the third round a = [6, 5, 4, 1, 3, 2];
The final result of the fourth round a = [ 6, 5, 4, 3, 1, 2];
The final result of the fifth round a = [6, 5, 4, 3, 2, 1];
The following is the reconstruction method:

Copy code The code is as follows:

Array.prototype.fst = function(fn){
var fn = fn || function(a, b){ return a > b;};
for(var i=0; ifor(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 actual demo

[Ctrl A select all Note:
If you need to introduce external Js, you need to refresh to execute <script> 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; }; </script>]<script> var a = [3, 1, 5, 6, 4, 2]; //a.fst(); //alert(a.fst().join()); alert(a.fst(function(a, b){ return a < b}).join()); //alert(a.fst(function(a, b){ return a - b}).join()); //alert(a.sort(function(){ return 1})); //alert(a.fst(function(){ return 1})); </script>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template