首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >插入排序-最佳/平均分析

插入排序-最佳/平均分析
EN

Stack Overflow用户
提问于 2016-12-18 08:37:02
回答 1查看 285关注 0票数 0

关于塞奇威克教授的插入排序讲课

我知道了,

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

我也知道,

最好的情况--如果数组按升序排列,插入排序将使N-1比较和零交换。

如果我分析伪码,

代码语言:javascript
复制
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比较。

我的理解正确吗?

EN

回答 1

Stack Overflow用户

发布于 2016-12-18 08:51:06

啊,还需要更多的数学。

您是否意识到插入排序所执行的掉期数量正是输入中存在的反转次数?

倒置:索引对(i,j)是如果i<j but a[i]>a[j]的逆。

代码语言:javascript
复制
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

我有多少指数?

代码语言:javascript
复制
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 

顺便说一句,我猜你知道this...but still.why 1+2+.n-1=n*(n-1)/2

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41206705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档