算法系列:2. 插入排序

/**
 * @Desc 插入排序 
 * 时间复杂度:O(n^2)
 * 从第二个数开始往前比
 * 有比第二个数小的,往后排
 * 从第三个数开始往前比,有比它大的往后排
 * 以此类推 进行到最后一个数
 */
Array.prototype.insertSort = function() {
    
    
    for (let i=1;i<this.length; i+=1) {
    
    
        let temp = this[i];
        let j = i;

        while (j > 0) {
    
    
            if(this[j-1] > temp) {
    
    
                this[j] = this[j -1];
            } else {
    
    
                break;
            }

            j -= 1;
        }

        // j即为 要插入的位置
        this[j] = temp;
    }
}

猜你喜欢

转载自blog.csdn.net/RedaTao/article/details/120534487