向Array中添加插入排序

插入排序思路

从第二个元素开始和它前面的元素进行比较,如果比前面的元素小,那么前面的元素向后移动,否则就将此元素插入到相应的位置。

插入排序实现

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

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