js 重构Array的sort排序方法


这个排序是进行两两比较。
拿这个数组进行降序排列var a = [3, 1, 5, 6, 4, 2];
第一轮比较:用第一个数值和本数组的其他元素进行比对
3比1
3比5 //5大,所以所以进行交换 得a = [5, 1, 3, 6, 4, 2];
5比6 //交换 得a = [6, 1, 3, 5, 4, 2];
6比4
6比2
第一轮最终结果 a = [6, 1, 3, 5, 4, 2];
第二轮比较:用第二个数值和这个数值之后的元素进行对比
1比3 //交换 得a = [6, 3, 1, 5, 4, 2];
3比5 //交换 得a = [6, 5, 1, 3, 4, 2];
5比4
5比2
第二轮最终结果 a = [6, 5, 1, 3, 4, 2];
就这样依次进行交换
第三轮最终结果 a = [6, 5, 4, 1, 3, 2];
第四轮最终结果 a = [6, 5, 4, 3, 1, 2];
第五轮最终结果 a = [6, 5, 4, 3, 2, 1];
下面是重构的方法:
复制代码 代码如下:

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;
};

查看实际演示

[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3