已知堆排序的部分代码如下,勿改动,请补充实现堆排序函数void HeapSort(int n);。
#include<iostream>
using namespace std;
const int MaxSize=100;
class List
{
private:
int r[MaxSize+1];
int n;
public:
List(){n=0;} //empty list
void InsertR(int k) //表尾插入
{ r[++n]=k;}
void Display(); //display
void HeapSort() { HeapSort(n); } //HeapSort
void HeapSort(int n);
};
void List::Display()
{
for(int i=1;i<=n;i++)
cout<<r[i]<<" ";
cout<<"\n";
}
int main()
{
List L;
while(1)
{
int k;
cin>>k;
if(!k) break;
L.InsertR(k);
}
L.Display();
L.HeapSort();
L.Display();
return 0;
}
输入
输出
样例输入
12 21 32 2 4 24 21 432 23 9 0
样例输出
12 21 32 2 4 24 21 432 23 9
2 4 9 12 21 21 23 24 32 432
具体过程可参考
https://blog.csdn.net/m0_46975599/article/details/112125116
//已知堆排序的部分代码如下,勿改动,请补充实现堆排序函数void HeapSort(int n);。
#include<iostream>
using namespace std;
const int MaxSize=100;
class List
{
private:
int r[MaxSize+1];
int n;
public:
List(){n=0;} //empty list
void InsertR(int k) //表尾插入
{ r[++n]=k;}
void Display(); //display
void HeapSort()
{ HeapSort(n);
for(int k=n;k>1;k--)
{
swap(r[k],r[1]);
//本来最大数在上面,但是由于交换,使得最大数变成最后的节点,以至于变成了小堆
HeapSort(k-1);
}
} //HeapSort
void HeapSort(int n);
};
void List::Display()
{
for(int i=1;i<=n;i++)
cout<<r[i]<<" ";
cout<<"\n";
}
void List::HeapSort(int n)
{
for(int i=n/2;i>0;i--)
{
r[0]=r[i];
for(int j=i*2;j<=n;j*=2) //一直向下筛选。i下移
{
if(j<n&&r[j]<r[j+1])//比较左右孩子大小,如果左孩子小于右孩子那么j值
j++;
if(r[0]>=r[j])//已经满足大 头 跳出
break;
else //不满足小头 进行交换
{
r[i]=r[j];
i=j;//孩子当作父亲节点 继续向下筛选
}
r[i]=r[0];
}
}
}
int main()
{
List L;
while(1)
{
int k;
cin>>k;
if(!k) break;
L.InsertR(k);
}
L.Display();
L.HeapSort();
L.Display();
return 0;
}