zoukankan      html  css  js  c++  java
  • Insertion sort

    Input: A sequence of n numbers [a1,a2,...,an]

    Output: a permutation (reordering) [a1',a2',...,an'] of the input sequence such that a1' <=a2' <= ... <= an'.

    array = [2,4,5,22,6,34,2,5,1,3,6,9,7,8]
    print array
    def insertSort(array):
        for i in xrange(1,len(array)):
            # key as a temp room for a certain element in a certain step
            key = array[i] 
            j  = i - 1
            while j >=0 and array[j] > key:
                array[j+1]  = array[j]
                j = j - 1
            array[j+1] = key # loop still running till last step, so j = j - 1
            print array
        return array
    
    insertSort(array)
    # output
    
    [2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 4, 5, 6, 22, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 4, 5, 6, 22, 34, 2, 5, 1, 3, 6, 9, 7, 8]
    [2, 2, 4, 5, 6, 22, 34, 5, 1, 3, 6, 9, 7, 8]
    [2, 2, 4, 5, 5, 6, 22, 34, 1, 3, 6, 9, 7, 8]
    [1, 2, 2, 4, 5, 5, 6, 22, 34, 3, 6, 9, 7, 8]
    [1, 2, 2, 3, 4, 5, 5, 6, 22, 34, 6, 9, 7, 8]
    [1, 2, 2, 3, 4, 5, 5, 6, 6, 22, 34, 9, 7, 8]
    [1, 2, 2, 3, 4, 5, 5, 6, 6, 9, 22, 34, 7, 8]
    [1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 9, 22, 34, 8]
    [1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 22, 34]

    Here, we use loop invariants to help us understand why an algorithms is correct:

    Initialization: It is true prior to the first iteration of the loop;

    Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration

    Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.

    This is the first alogorithm, and its idea behind is simple and naive: for aj, we just compare it with the element just before it ( change, if a(j-1) >a(j) and then exchange index, else stop and go to sort next element(a(j+1)); loop till to all the elements done~

  • 相关阅读:
    zoj3888 找第二大
    zoj3882 博弈
    字典树小总结
    hdu2222 字典树
    hdu1247 字典树
    开放融合 | “引擎级”深度对接!POLARDB与SuperMap联合构建首个云原生时空平台
    阿里HBase高可用8年“抗战”回忆录
    最佳实践 | RDS & POLARDB归档到X-Pack Spark计算
    今日头条在消息服务平台和容灾体系建设方面的实践与思考
    饿了么监控系统 EMonitor 与美团点评 CAT 的对比
  • 原文地址:https://www.cnblogs.com/vpegasus/p/Insertion_algorithm.html
Copyright © 2011-2022 走看看