博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
堆的排序研究
阅读量:4497 次
发布时间:2019-06-08

本文共 2315 字,大约阅读时间需要 7 分钟。

今天偶然看到一个找出N个数中最大的前500个数,一个不错的解法是使用堆来进行选择,每一次读取一个数判断是否需要放到堆中,这样比较下来就可以找到最大或最小的前500个数了,自己晚上就参考别人的代码写了一个最小堆的结构,后期继续补充。

View Code
#include 
#include
typedef int ElemType; struct heap{
ElemType *num; int heapsize; int maxSize; }; struct heap HP; int init_heap(int size) {
if(size <= 0){
printf("not allow empty heap\n"); return -1; } HP.num = malloc(size*sizeof(ElemType)); if(HP.num == NULL){
printf("malloc failed\n"); exit(1); } HP.heapsize = 0; HP.maxSize = size; return 0; } void exit_heap() {
if(HP.num != NULL){
free(HP.num); HP.num = NULL; HP.heapsize = 0; HP.maxSize = 0; } } int isEmpty() {
if(HP.heapsize == 0){
return 1; }else{
return 0; } } int insert_heap(ElemType arg) {
int ct; if(HP.heapsize == HP.maxSize){
ElemType* pe; pe = realloc(HP.num,HP.heapsize*2*sizeof(ElemType)); if(pe == NULL){
printf("realloc heap failed\n"); exit(1); } HP.num = pe; HP.maxSize = HP.heapsize*2; } HP.num[HP.heapsize] = arg; HP.heapsize++; ct = HP.heapsize - 1; while(0 != ct){
int j = (ct - 1) /2; if(arg > HP.num[j]) break; HP.num[ct] = HP.num[j]; ct = j; } HP.num[ct] = arg; return 1; } ElemType delete_heap() {
ElemType temp,x; int i,j; if(HP.heapsize == 0){
printf("heap has been empty\n"); exit(1); } x = HP.num[0]; HP.heapsize--; if(HP.heapsize == 0){
return x; } temp = HP.num[HP.heapsize]; i = 0; j = 2*i + 1; while(j <= HP.heapsize-1){
if((j< HP.heapsize-1) && (HP.num[j] > HP.num[j+1])){
j++; } if(temp <= HP.num[j] ){
break; } HP.num[i] = HP.num[j]; i = j; j = 2*i + 1; } HP.num[i] = temp; return x; } int main() {
int i; ElemType it; printf("input:"); for(i=0;i<10;i++){
scanf("%d",&it); insert_heap(it); } for(i=0;i<10;i++){
printf("%d ",delete_heap()); } printf("\n"); return 0; }

 

转载于:https://www.cnblogs.com/gogly/archive/2012/02/16/2353443.html

你可能感兴趣的文章
[转]How to compile GDB for iOS!
查看>>
redis windows安装
查看>>
python有序字典OrderedDict()
查看>>
sql 检索字符串
查看>>
常用正则表达式
查看>>
HDU 4280 最大流Dinic算法优化
查看>>
八大排序算法
查看>>
why dropout work?
查看>>
小白成长记-----python实现注册的小程序
查看>>
Codeforces Round #151 (Div. 2)总结
查看>>
cin问题 分类: c++ 2014-08-02 2...
查看>>
PHP 中文字符串相关
查看>>
开始搭建 myBatis.net + Spring.net + asp.net mvc 3 + easyUI 开发平台
查看>>
vue-cli的项目中关于axios的全局配置
查看>>
动软.Net代码生成器
查看>>
Redis使用
查看>>
json数组
查看>>
【转】nginx 499错误的原因及解决办法
查看>>
用C语言实现最小二乘法算法
查看>>
js学习笔记一
查看>>