插入排序算法分析

插入排序伪代码:

INSERT-SORT
for j=2 to A.length
    key = A[j]
    //insert A[j] into the sorted sequence A[1..j-1].
    i=j-1
    while i>0 and A[i]>key
        A[i+1] = A[i]
        i=i-1
    A[i+1] = key

算法执行流程&代价分析

INSERT-SORT                                                                代价                       次数

for j=2 to A.length                                                         c1                         n                                                                       

    key = A[j]                                                              c2                        n-1

    //insert A[j] into the sorted sequence A[1..j-1].                       0                          n-1

    i=j-1                                                                   c3                        n-1

    while i>0 and A[i]>key                                                  c5                       (n(n+1)/2)-1

        A[i+1] = A[i]                                                       c6                       (n(n+1)/2)-1 

     i=i-1                                      c7              (n(n+1)/2)-1
A[i+1] = key                                                c8               n-1

最好情况:

 

最坏情况:

posted @ 2015-07-02 09:05  b13272012771  阅读(133)  评论(0编辑  收藏  举报