1. 程式人生 > >Insertion sort and Merge sort

Insertion sort and Merge sort

 Insertion sort(直接插入排序)

pseudocode:

                                                insertion sort (a,n)

 for j = 2 to n
         key = a[j]
         i = j -1
         while i>0 && a[i] >key
                   a[i+i] = a[i]
                   i = i-1
         a[i+1] = key


關於o 標記法

    數學上: o(g(n)) = {f(n): 存在正常數c1,c2,n0使得對於所有的n>=n0 都有 0<=c1*g(n)<=f(n)<=c2*g(n) }

   工程學上: 削減低階元素;忽略係數

                       例如: 3N^3 + 90n^2 - 5n +100 = o(n^3)

    最壞時間複雜度:最壞情況下,對於每個j都需要排j次:      t(n)=∑o(j) =o(n^2)

    平均時間複雜度: t(n)=∑o(j/2) =o(n^2)

Merge srot (歸併排序)

pseudocode

                                merge sort a(1,....,n)

if n = 1 ,done
recursively sort a(1,n/2)and a(n/2+1,n)
merge the two sort list

歸併排序的時間複雜度分析首先,先針對每一步進行單獨分析:

if n = 1 ,done                                                                              o(1)

recursively sort a(1,n/2)and a(n/2+1,n)                                2T(n/2)

merge the two sort list                                                             o(n)

於是歸併排序的時間複雜度為:T(n) = o(1) + 2T(n/2) + o(n)

忽略o(1), 因此歸併排序的時間複雜度現在轉化為 求解:  T(n)= 2T(n/2) + c*n 要求c>0

轉化為地歸樹為

                       cn
                       /   \
              T(n/2)  T(n/2)                                 

進一步                     

                      cn                                                  

                   /           \                                           

            cn/2             cn/2                                         

        /          \           /         \                                 

 T(n/4)     T(n/4)   T(n/4)   T(n/4)                               

 最終
                     cn                                                                                              

                 /            \                                                                                                                        

             cn/2             cn/2                     樹的深度為lgn                                          

         /            \          /         \                                                                                                    

  cn/4         cn/4   cn/4     cn/4                                                                        

    ....            ....       ...           ....                                        

 o(1)                                         共有n個葉子節點,因此 對於葉子節點來說時間複雜度為o(n)

在求最壞時間複雜度時,將樹的每一層近似的看成與葉子節點的時間複雜度相同,因此求解歸併排序的時間複雜度為 o(nlgn)