#include<stdio.h>
#include<iostream>
#define MAXL 100
typedef int KeyType;
typedef char InfoType;
typedef struct
{
KeyType key;
InfoType data;
}RecType;
void swap(RecType &x, RecType &y)
{
RecType temp;
temp = x;
x = y;
y = temp;
}
void CreateList(RecType R[], KeyType keys[], int n)
{
for (int i =1 ; i <= n; i++)
{
R[i].key = keys[i-1];
}
}
void Display(RecType R[], int n)
{
for (int i = 1; i <= n; i++)
{
printf("%d", R[i].key);
}
printf("\n");
}
void DispHeap(RecType R[], int i, int n)
{
if (i <= n)
printf("%d", R[i].key);
if (2 * i <= n || 2 * i + 1 < n)
{
printf("(");
if (2 * i <= n)
DispHeap(R, 2 * i, n);
printf(",");
if (2 * i + 1 <= n)
DispHeap(R, 2 * i + 1, n);
printf(")");
}
}
void sift(RecType R[], int low, int high)
{
int i = low, j = 2 * i; //R[j]是R[i]的左孩子
RecType temp = R[i];
while (j <= high)
{
if (j<high && R[j].key<R[j + 1].key) //若右孩子较大,把j指向右孩子
j++; //变为2i+1
if (temp.key<R[j].key)
{
R[i] = R[j]; //将R[j]调整到双亲结点位置上
i = j; //修改i和j值,以便继续向下筛选
j = 2 * i;
}
else break; //筛选结束
}
R[i] = temp; //被筛选结点的值放入最终位置
}
void HeapSort(RecType R[], int n)
{
int i,j,count=1;
for (i = n / 2; i >= 1; i--) //循环建立初始堆,调用sift算法 n/2 次
sift(R, i, n);
printf("初始堆:"); DispHeap(R, 1, n); printf("\n");
for (i = n; i >= 2; i--) //进行n-1趟完成推排序,每一趟堆排序的元素个数减1
{
printf("第%d趟排序:", count++);
printf("交换%d与%d,输出%d ", R[i].key, R[1].key, R[1].key);
swap(R[i], R[1]);
printf("排序结果:");
for (j = 1; j <= n; j++)
printf("%2d", R[j].key);
printf("\n");
printf("\n");
sift(R, 1, i - 1);//对R[1..i-1]进行筛选,得到i-1个节点的堆
printf("筛选调整得到堆:");
DispHeap(R, 1, i - 1);
printf("\n");
}
}
int main()
{
int n = 10;
RecType R[MAXL];
KeyType a[] = { 6,8,7,9,0,1,3,2,4,5 };
CreateList(R, a, n);
printf("排序前:"); Display(R, n);
HeapSort(R, n);
printf("\n");
printf("排序后:"); Display(R, n);
system("pause");
return 1;
}
排序方法7---堆排序
最新推荐文章于 2022-12-23 14:44:16 发布