asfman
android developer
posts - 90,  comments - 213,  trackbacks - 0

<script>

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

    Array.prototype.bubbleSort = function()
    {
        for (var i = this.length - 1; i > 0; --i)
        {
            for (var j = 0; j < i; ++j)
            {
                if (this[j] > this[j + 1]) this.swap(j, j + 1);
            }
        }
    }
   
</script>
Array.prototype.bubbleSort = function(comp)
    {
        for (var i = this.length - 1; i > 0; --i)
        {
            for (var j = 0; j < i; ++j)
            {
                if (comp(this[j] , this[j + 1])) this.swap(j, j + 1);
            }
        }
    }

所以我传递闭包用它来取代真实的比较,注意看上面
我用comp(this[j], this[j+1])来取代this[j] > this[j+1]
这样this[j],this[j+1]的大小关系由comp函数的执行结果决定
和你讲完这个我就要睡了...
[1,3,4,2].bubbleSort(function(x,y){x>y});
就是按从大到小排列
[1,3,4,2].bubbleSort(function(x,y){x<y});
是从小到大排列
[1,3,4,2].bubbleSort(function(x,y){x.length<y.length});
是按字符串长度排列

<script language="javascript">
var a=[1,3,4,-1,2];
var b=a.slice(0);
function box(vArray,vMax)
{
var result=[];
function array_max( ){
   var i, max = this[0];
   for (i = 1; i < this.length; i++)
   {
   if (max < this[i])
   {
   max = this[i];
   var temp=i;
   }
   }
   return [max,temp];
}
Array.prototype.max = array_max;
while(vArray.length!=0)
{
var y=vArray.max();
result.push(y[0]);
vArray.splice(y[1],1);
}
if(vMax)
return result;
else
return result.reverse();
}
alert(box(a,true));
alert(box(b,false));

</script>

posted on 2007-04-03 00:00 汪杰 阅读(166) 评论(0)  编辑 收藏 引用 所属分类: javascript
只有注册用户登录后才能发表评论。

<2006年10月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

常用链接

留言簿(15)

随笔分类(1)

随笔档案(90)

文章分类(727)

文章档案(712)

相册

收藏夹

http://blog.csdn.net/prodigynonsense

友情链接

最新随笔

搜索

  •  

积分与排名

  • 积分 - 457932
  • 排名 - 6

最新随笔

最新评论

阅读排行榜

评论排行榜