Copyright (c)2016,烟台大学计算机与控制工程学院
* All rights reserved.
* 文件名称:项目1-6.cbp
* 作 者:王婧
* 完成日期:2016年12月15日
* 版 本 号:v1.0
* 问题描述: 验证堆排序
* 输入描述:无
#include <stdio.h>
#define MaxSize 20
typedef int KeyType; //定义关键字类型
typedef char InfoType[10];
typedef struct //记录类型
{
KeyType key; //关键字项
InfoType data; //其他数据项,类型为InfoType
} RecType; //排序的记录类型定义
//调整堆
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;
RecType temp;
for (i=n/2; i>=1; i--) //循环建立初始堆
sift(R,i,n);
for (i=n; i>=2; i--) //进行n-1次循环,完成推排序
{
temp=R[1]; //将第一个元素同当前区间内R[1]对换
R[1]=R[i];
R[i]=temp;
sift(R,1,i-1); //筛选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};//a[0]空闲,不作为关键字
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;
}
- #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/20151215175713901)
我的同类文章
- •2015-12-19
- •2015-12-19
- •2015-12-15
- •2015-12-15
- •2015-12-14
- •2015-12-19
- •2015-12-15
- •2015-12-15
- •2015-12-14
- •2015-12-14
更多文章
参考知识库
-
猜你在找
-
《C语言/C++学习指南》加密解密篇(安全相关算法)
-
C语言系列之 字符串压缩算法与结构体初探
-
C语言系列之 字符串相关算法
-
C语言系列之 递归算法示例与 Windows 趣味小项目
-
模板匹配的字符识别(OCR)算法原理
-
- 访问:22651次
- 积分:1450
- 等级:
![](https://i-blog.csdnimg.cn/blog_migrate/4e8bdafb2c68168a707c23e6ea2b71b8.png)
- 排名:千里之外
- 原创:100篇
- 转载:10篇
- 译文:0篇
- 评论:37条
暂无评论