向Array中添加改进的冒泡排序

改进冒泡思路

如果在某次的排序中没有出现交换的情况,那么说明在无序的元素现在已经是有序了,就可以直接返回了。

改进冒泡实现

Function.prototype.method = function(name, func){
    this.prototype[name] = func;
    return this;
};

Array.method('rBubbleSort', function(){
    var len = this.length,
        i, j, tmp, exchange;
    for(i=0; i<len; i++){
        exchange = 0;
        for(j=len-1; j>i; j--){
            if(this[j] < this[j-1]){
                tmp = this[j];
                this[j] = this[j-1];
                this[j-1] = tmp;
                exchange = 1;
            }
        }
        if(!exchange) return this;
    }
    return this;
});
原文地址:https://www.cnblogs.com/JChen666/p/3359042.html