69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include<stdlib.h>
#define N 14
typedef int KeyType;
typedef int InfoType;
typedef int SeqList;
typedef struct
{
KeyType key;
InfoType otherinfo;
}RecType;
void build_max_heap(RecType R[],int n); //建大根堆算法
void heapsort(RecType R[], int n); //堆排序的算法
//void main()
int main()
{
int i,n;
RecType R[N];
printf("请输入将要排序元素的个数:");
scanf("%d", &n);
printf("\n");
for(i=0; i < n; i++)
{
printf("请输入第%d个数为:",i+1);
scanf("%d",&R[i].key);
scanf("%d",&R[i].otherinfo);
}
printf("排序前的数据:\n"); //打印排序前的数据
for (int i = 0; i < n; i++)
{
printf("%d ",R[i].key);
printf("%d ",R[i].otherinfo);
}
heapsort(R, n);
printf("\n排序后的数据:\n"); //打印排序后的数据
for (i = 0;i < n;i++) {
printf("%d ",R[i].key);
printf("%d ",R[i].otherinfo);
}
printf("\n");
system("pause");
}
void max_heapify(RecType R[],int k,int m) //用筛选法调整堆
{
RecType t;
int i,j,x;
t=R[k];
x=R[k].key;
i=k;
j=2*i;
while(j<=m)
{
if (j<m && R[j].key<R[j+1].key)
j=j+1;
if(x<R[j].key)
{
R[i]=R[j];
i=j;
j=2*i;
}
else
break;
}
R[i]=t;
}
void build_max_heap(RecType R[],int n) //建大根堆算法
{
int i;
for (i = n/2;i >= 1;i--)
max_heapify(R,i,n);
}
void heapsort(RecType R[], int n) //堆排序的算法
{
//int i,n;
int i;
build_max_heap(R,n);
for (i = n;i >1;i--)
{
R[0] = R[1];
R[1] = R[i];
R[i] = R[0];
max_heapify(R,1,i-1);
}
}