【问题标题】:Insertion sort - Best/Average analysis插入排序 - 最佳/平均分析
【发布时间】:2016-12-18 17:17:30
【问题描述】:

关于引用 Sedgewick 教授的插入排序 lecture

我知道了,

Proposition:要对具有不同键的随机排序数组进行排序,插入排序平均使用 ~(1/4 )N^2 次比较和 ~(1/4 )N^2 次交换。

我也知道了,

Best case - 如果数组是升序的,插入排序进行 N-1 次比较和零次交换

如果我分析伪代码,

int n = array.length;
for(int i=0; i < n; i++){
  for(int j=i; j>0; j--){
    if(less(a[j], a[j-1]))
      swap(array, j, j-1);
    else
      break; // Is N^2/4 due to break statement?
  }
} 

问题:

所以,

由于break 声明避免进一步比较,插入排序在平均情况下执行 (N^2)/4 次比较,在最佳情况下执行 N-1 次比较。

我的理解正确吗?

【问题讨论】:

    标签: algorithm sorting insertion-sort


    【解决方案1】:

    啊,还需要更多的数学知识。

    您是否意识到插入排序执行的交换次数正是输入中存在的反转次数?

    反转:如果i&lt;j but a[i]&gt;a[j],索引对 (i,j) 是反转。

    So I(i,j) = 1 if (i,j) is inversion
              = 0 if (i,J) is not an inversion
    
    Now you have to get the expectation of this to get the average case
    E[I]= Sum(E[I_{i,j}) = Sum over i and j such that i<j [(1/2)]= 1/2*nC2=n*(n-1)/2*1/2~n^2/4
    
    Why E[I_(i,j)]=1/2?
        E[I_(i,j)]=P(I_(i,j)=1)*I_(i,j)+P(I_(i,j)=0)*I_(i,j)
                  = 1/2*1+1/2*0
                  = 1/2
    

    i 有多少个索引

    1 2 3 4 .. n
    For 1 there is 0 such indices
    For 2 there is 1 such index [1]
    For 3 there is 2 such index [1,2]
    ..
    For n there is 1 such index [1,2,..n-1]
    So total = 0+1+2..+n-1= n*(n-1)/2 
    

    顺便说一句,我猜你知道这个......但仍然。为什么 1+2+..n-1=n*(n-1)/2

    Let the sum be S= 1+2+3+...+n-1
                   S= n-1+n-2+....1
                -----------------------
                  2*S= (n-1+1)+(n-2+2)...(1+n-1)
                     = n *n*n...n-1 times
                     = n*(n-1)
                So S = n*(n-1)/2
    

    【讨论】:

    • 您的答案的第 4 行似乎有错字
    • @overexchange.:现在检查答案。
    • 是的,在插入排序中,执行的交换次数与选择排序不同。
    • @overexchange.: 是的,你最好的案例逻辑是正确的。
    • 我试图理解外行的方法,我说break 声明在平均/最坏情况比较中的表现不同。但是多少钱?(N ^ 2)/ 4。要回答这个问题,我们肯定需要数学
    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 2018-03-20
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多