#include<iostream>
using namespace std;
#define MAX 100 //假定最大长度为100
#define OK 1
typedef int KeyType; //假定数据类型为int
typedef struct {
KeyType key; //关键字项
}RedType; //记录类型
typedef struct {
RedType r[MAX + 1]; //r[0]用作哨兵
int length; //表长
}SqList; //表的类型
int InitList_Sq(SqList& L); //初始化顺序表
void HeapAdjust(SqList& H, int s, int m); //建立大根堆
void HeapSort(SqList& H); //堆排序
void print(SqList L); //输出顺序表
int main()
{
SqList L;
InitList_Sq(L);
HeapSort(L);
print(L);
return 0;
}
int InitList_Sq(SqList& L)
{
int n, k = 1; //n为待输入数,k为计数器
L.length = 0; //表长初始化为0
while (1)
{
cin >> n;
if (n == -1) //假设输入-1为结束标志
break;
L.r[k++].key = n;
L.length++; //表长+1
}
return OK;
}
void HeapAdjust(SqList& H, int s, int m)
{
RedType rc = H.r[s];
for (int j = 2 * s; j <= m; j *= 2) //沿key较大的孩子结点向下筛选
{
if (j < m && H.r[j].key < H.r[j + 1].key) //j为key较大的记录的下标
++j;
if (rc.key >= H.r[j].key) //rc应插入在位置s上
break;
H.r[s] = H.r[j];
s = j;
}
H.r[s] = rc; //插入sc
}
void HeapSort(SqList& H)
{
for (int i = H.length / 2; i > 0; --i) //把H.r[1...h.length]建成大根堆
HeapAdjust(H, i, H.length);
for (int i = H.length; i > 1; --i)
{
RedType temp = H.r[1]; //将堆顶记录和当前未经排序子序列H.r[1...i]中最后一个记录交换
H.r[1] = H.r[i];
H.r[i] = temp;
HeapAdjust(H, 1, i - 1); //把H.r[1...i - 1]重新调整为大根堆
}
}
void print(SqList L)
{
for (int i = 1; i <= L.length; i++)
cout << L.r[i].key << ' ';
cout << endl;
}
选择排序-堆排序
最新推荐文章于 2024-11-04 13:52:23 发布