返回信息流```cpp
#include<iostream>
using namespace std;
void weihu(int a[],int root,int low,int high)
{
int l=2*root+1;
int r=2*root+2;
int large=0;
if(l<=high&&a[l]>a[root])
large=l;
else
large=root;
if(r<=high&&a[r]>a[large])
large=r;
if(large!=root)
{
swap(a[large],a[root]);
weihu(a,large,low,high);
}
}
void Build(int a[],int n)
{
for(int i=n/2-1;i>=0;i--)
weihu(a,i,0,n-1);
}
void Sort(int a[],int n)
{
Build(a,n);
for(int i=n-1;i>=0;i--)
{
swap(a[0],a[i]);
weihu(a,0,0,i-1);
}
}
int main()
{
int a[]={3,2,6,4,8,6,5,3,-2,-2,9,0};
int n=sizeof(a)/sizeof(int);
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
Sort(a,n);
cout<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
}
```
_____________________________________________________
想把上边的整个数组堆排序改成一个可以用下标控制排序范围的堆排序,改了半天没成功
感觉维护函数不用变,要改的就是建堆函数和排序函数,应该怎么改才对?
下边是我改的,不对
```cpp
void Build(int a[],int l,int r)
{
for(int i=(r-l+1)/2-1;i>=0;i--)
weihu(a,i,l,r);
}
void Sort(int a[],int l,int r)
{
Build(a,0,r-l);
for(int i=r;i>=l;i--)
{
swap(a[l],a[i]);
weihu(a,0,l,i-1);
}
}
```
这是一条镜像帖。来源:北邮人论坛 / cpp / #95074同步于 2017/4/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
堆排序问题
bingge
2017/4/10镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
[0,n-1]确实没问题,但是[1,n-2]就不行了
【 在 solosseason 的大作中提到: 】
: 楼主的代码应该是没问题,main函数里调用修改后的sort就可以
: [code=c]
: Sort(a,0,n-1);
: ...................
我想实现的就是在一个数组里,比如
```
int a[]={30,20,50,10,40};
```
如果是上边的堆排序,那么输出: 10 20 30 40 50
而我想只对数组内的一个范围进行排序,比如只对下标[1,3]内排序,那么输出应该是:30 10 20 50 40
我就是想实现这个功能
【 在 wok 的大作中提到: 】
: 堆顶的下标得是0啊,你这改了堆顶啊
以你想进行排序的范围为例,你现在的堆顶下标为1,他的左子树是2*1+1,右子树是2*1+2;你这下标就对不上了啊,下标2是下标0的右子树啊
【 在 bingge 的大作中提到: 】
: 我想实现的就是在一个数组里,比如
: [md]
: ```
: ...................