Why is insertion sort Θ(n^2) in the average case?

前端 未结 3 1040
盖世英雄少女心
盖世英雄少女心 2021-01-30 05:32

Insertion sort has a runtime that is Ω(n) (when the input is sorted) and O(n2) (when the input is reverse sorted). On average, it runs in Θ(n2

3条回答
  •  隐瞒了意图╮
    2021-01-30 06:25

    For fun I wrote a program which ran through all data combinations for a vector of size n counting comparisons and found that the best case is n-1 (all sorted) and the worst is (n*(n-1))/2.

    Some results for different n:

      n min     ave     max ave/(min+max) ave/max
    
      2   1     1         1        0.5000
      3   2     2.667     3        0.5334
      4   3     4.917     6        0.5463
      5   4     7.717    10        0.5512
      6   5    11.050    15        0.5525
      7   6    14.907    21        0.5521
      8   7    19.282    28        0.5509
      9   8    24.171    36        0.5493
     10   9    29.571    45        0.5476
     11  10    35.480    55        0.5458
     12  11    41.897    66        0.5441
    

    It seems the average value follows min closer than it does max.

    EDIT: some additional values

     13  12    48.820    78        0.5424        
     14  13    56.248    91        0.5408
    

    EDIT: value for 15

     15  14    64.182   105        0.5393
    

    EDIT: selected higher values

     16  15    72.619   120        -       0.6052
     32  31   275.942   496        -       0.5563
     64  63  1034.772  1953        -       0.5294
    128 127  4186.567  8128        -       0.5151
    256 255 16569.876 32640        -       0.5077
    

    I recently wrote a program to compute the average number of comparisons for insertion sort for higher values of n. From these I have drawn the conclusion that as n approaches infinity the average case approaches the worst case divided by two.

提交回复
热议问题