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~

  • 相关阅读:
    jdbc-------JDBCUtil类 工具类
    jdbc --- javabean
    MapReduce 找出共同好友
    mapReducer 去重副的单词
    用户定义的java计数器
    mapReducer第一个例子WordCount
    win10 Java环境变量,hadoop 环境变量
    Writable序列化
    io 流操作hdfs
    [常用命令]OSX命令
  • 原文地址:https://www.cnblogs.com/vpegasus/p/Insertion_algorithm.html
Copyright © 2011-2022 走看看