Archive for 六月, 2011

重构Array的sort方法

星期四, 六月 16th, 2011
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;
};
 

最近忙学车冷漠了博客。活力控 以后哟勤奋点哦

星期三, 六月 15th, 2011

RT