问题描述:
/*
* Copyright (c)2015级,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:11.cpp
* 作 者:彭友程
* 完成日期:2016年12月15日
* 版 本 号:v1.0
*问题描述:验证堆排序,完成测试。
*输入描述:无
*程序输出:测试数据
*/
选择排序之堆排序:
实现代码:
- #include <stdio.h>
- #define MaxSize 20
- typedef int KeyType;
- typedef char InfoType[10];
- typedef struct
- {
- KeyType key;
- InfoType data;
- } RecType;
-
-
- void sift(RecType R[],int low,int high)
- {
- int i=low,j=2*i;
- RecType temp=R[i];
- while (j<=high)
- {
- if (j<high && R[j].key<R[j+1].key)
- j++;
- if (temp.key<R[j].key)
- {
- R[i]=R[j];
- i=j;
- j=2*i;
- }
- else break;
- }
- R[i]=temp;
- }
-
-
- void HeapSort(RecType R[],int n)
- {
- int i;
- RecType temp;
- for (i=n/2; i>=1; i--)
- sift(R,i,n);
- for (i=n; i>=2; i--)
- {
- temp=R[1];
- R[1]=R[i];
- R[i]=temp;
- sift(R,1,i-1);
- }
- }
-
- int main()
- {
- int i,n=10;
- RecType R[MaxSize];
- KeyType a[]= {0,6,8,7,9,0,1,3,2,4,5};
- for (i=1; i<=n; i++)
- R[i].key=a[i];
- printf("排序前:");
- for (i=1; i<=n; i++)
- printf("%d ",R[i].key);
- printf("\n");
- HeapSort(R,n);
- printf("排序后:");
- for (i=1; i<=n; i++)
- printf("%d ",R[i].key);
- printf("\n");
- return 0;
- }
运行结果:
![](https://img-blog.csdn.net/20161215112315102)
知识点总结:
堆排序的实现代码。