有一个语句不是很明白……

apices 2003-02-18 03:53:50
void Insert(int a[],int n,const int &x)
{
for(int i=n-1;i>=0 && x<a[i];--i)
a[i+1]=a[i];
a[i+1]=x;
} //数组a以升序排列,将x插入a中

void InsertionSort(int a[],int n)
{
for(int i=1;i<n;++i)
{
int temp=a[i];
Insert(a,i,temp); //#1
}
}
InsertionSort是一个改进的插入排序,这样可以减少一些不必要的操作,但是不知道#1为什么这么用,不解……
...全文
24 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
apices 2003-02-19
  • 打赏
  • 举报
回复
virginsoldier(北欧野马——哈根)说的有道理,似乎的确是这样
aash0 2003-02-18
  • 打赏
  • 举报
回复
up
virginsoldier 2003-02-18
  • 打赏
  • 举报
回复
有个问题,就是i是在for中声明的,它的作用域应该仅限于for循环中呀!for循环结束后的a[i+1]=x;中的i应该没有生命才对呀!
apices 2003-02-18
  • 打赏
  • 举报
回复
上面的我知道,但是
a[]={4,3,2,5,1} i=1,temp=3
a[]={3,4,2,5,1} i=2,temp=2
这里4和3是怎么调换的,不清楚
wuhuar 2003-02-18
  • 打赏
  • 举报
回复
a[]={4,3,2,5,1} i=1,temp=3
a[]={3,4,2,5,1} i=2,temp=2
a[]={2,3,4,5,1} i=3,temp=5
a[]={2,3,4,5,1} i=4,temp=1
a[]={1,2,3,4,5}
apices 2003-02-18
  • 打赏
  • 举报
回复
哪位大侠能以这个例子a[]={4,3,2,5,1}讲解一二呀……?实在不明白:(
cupidvenus 2003-02-18
  • 打赏
  • 举报
回复
注意
void Insert(int a[],int n,const int &x)
中的说明const int &x
当然在InsertionSort就得用
int temp=a[i];
Insert(a,i,temp);
了,否则又怎么能改得了a[i]的值呢?
apices 2003-02-18
  • 打赏
  • 举报
回复
假如:a[]={4,3,2,5,1}
i=1:temp=a[1] ---> Insert(a,1,a[1])

for(int i=0;i>=0 && x<a[i];--i)
a[i+1]=a[i]; //a[1]=a[0]=4
a[i+1]=x; //a[1]=a[1]=4 or 3 ? a[0]呢?
solrac 2003-02-18
  • 打赏
  • 举报
回复
把A[]数组排序!
windcsn 2003-02-18
  • 打赏
  • 举报
回复
不对是
i=1:temp=a[1] ---> Insert(a,1,a[1])

for(int i=0;i>=0 && x<a[i];--i)
apices 2003-02-18
  • 打赏
  • 举报
回复
555,还是不太明白
i=1:temp=a[1] ---> Insert(a,1,a[1])

for(int i=1;i>=0 && x<a[i];--i)
a[i+1]=a[i];
a[i+1]=x;
可是这里x=a[1],无法小于a[i],好像执行不下去呀
windcsn 2003-02-18
  • 打赏
  • 举报
回复
当然
apices 2003-02-18
  • 打赏
  • 举报
回复
InsetionSort是不是对原数组进行排序,而没有插入其它值呀?
windcsn 2003-02-18
  • 打赏
  • 举报
回复
调用上面的排序算法,很正常啊,没有什么不解的吧!
思路是:先按顺序得到第几个数,然后和数组的元素比较,按照一定的顺序排列,插入相应的位置,修改i的值,为了对已经排序的不在排序了

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧