针对JS对象数组的Array排序实现

 这里只实现了冒泡排序和快速排序,一般来说也够用了

 点击下载此文件

/*
 * 对Array进行排序
 */
 
var CMPMETHOD = {
  btTimeCmp: function(a, b) {
    a=a.replace("天", "");
    b=b.replace("天", "");
    var as = a.split("年");
    var bs = b.split("年"); 

    var ayear = as.length > 1 ? as[0] : 0;
    var aday  = as.length > 1 ? as[1] : parseInt(as[0]);

    var byear = bs.length > 1 ? bs[0] : 0;
    var bday  = bs.length > 1 ? bs[1] : parseInt(bs[0]);

    var va = ayear * 365 + parseInt(aday);
    var vb = byear * 365 + parseInt(bday);
    
    if (va > vb ) return 1;
    if (va < vb ) return -1;
    if (va == vb) return 0;
  },
  numberCmp: function(a, b) {
    a = parseFloat(a);
    b = parseFloat(b);
    return CMPMETHOD.commonCmp(a, b);
  },
  commonCmp: function(a, b){
    if (a < b) return -1;
    if (a == b) return 0;
    if (a > b) return 1;
  }
}

Array.prototype.swap = function(i, j) {
  var temp = this[i];
  this[i]  = this[j];
  this[j]  = temp;
}

Array.prototype.quickSort = function() {
  var s=null, e=null, k=null, cmp=CMPMETHOD.commonCmp;
  if (arguments.length == 1) {
    s = null; e = null; k =arguments[0];
  }

  if (arguments.length == 2 ) {
    s = arguments[0];
    e = arguments[1];
  }

  if (arguments.length == 3) {
    s = arguments[0];
    e = arguments[1];
    k = arguments[2];
  }

  if (arguments.length == 4) {
    s = arguments[0];
    e = arguments[1];
    k = arguments[2];
    cmp = arguments[3];
  }

  if (s == null ) s = 0;
  if (e == null ) e = this.length-1;
  if (s >= e) return ;
  var x = s;    //基准索引
  var i, j;

  i = s; j = e;
  while(j > i) {
    for(; j>i; j--) {
      if (cmp(this[j][k], this[x][k]) < 0) {
        this.swap(j, x);
        x = j;
        break;
      }
    }

    for(; i



[本日志由 admin 于 2013-09-12 09:22 AM 编辑]

有什么问题可以加群,100852896
点击这里加入此群 在线提问
文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 5216
博主QQ: 友情链接请找我
QQ群: 灰色档案
返回顶部 关闭