首页 > 代码库 > 常用的排序算法

常用的排序算法

1.冒泡排序

Array.prototype.bubble = function(){    for(var i = 0; i < this.length; i++){        for(var j = i + 1; j < this.length; j++){            if(this[i] > this[j]){                var temp = this[i];                this[i] = this[j];                this[j] = temp;            }        }    }    return this;}

2.快速排序

Array.prototype.quick = function(){    if(this.length <= 1) return this;    var left = [];    var right = [];    var first = this[0];    for(var i = 1; i < this.length; i++){        if(this[i] > first){            right.push(this[i])        }else{            left.push(this[i])        }    }    return [].concat(left.quick(),first,right.quick())}

3.归并排序

Array.prototype.merge = function(){    var sort = function(left,right){        var final = [];        while(left.length && right.length){            final.push(left[0] <= right[0] ? left.shift() : right.shift())        }        return final.concat(left,right)    }    var length = this.length;    if(length < 2) return this;    var mid = parseInt(length / 2,10)    return sort(this.slice(0,mid).merge(),this.slice(mid).merge())}

排序算法其实用得时候不是很多,但还是需要掌握常用的几种,总结下来,经(dui)常(fu)复(mian)习(shi)。

常用的排序算法