min_heapsort.h

/*
最小优先级队列的实现,为了算法描述方便,数组下标从1开始,下标为0的元素舍弃不用
author:wuzuquan
last_modify:2008-1-11
*/
#include <stdio.h>
#include <limits.h>
#define PARENT(i) ((i)>>1)
#define LEFT(i) ((i)<<1)
#define RIGHT(i) ((LEFT(i))+1)

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
 *x = *y;
 *y = temp;
}

int heap_size;
int length;

void min_heaplfy(int *a,int i)
{//使以i为根的子树成为最小堆
 int left=LEFT(i);
 int right=RIGHT(i);
 int smallest=0;
 if(left<=heap_size && a[left]<a[i])
  smallest=left;
 else
  smallest=i;
 if(right<=heap_size && a[right]<a[smallest])
  smallest=right;//select a smallest element
 if(smallest!=i)
 {
  swap(&a[i],&a[smallest]);
  min_heaplfy(a,smallest);
 }
}

void build_min_heap(int *a)
{//对每一个非叶子结点都调用一次min_heaplfy
 int i=0;
 heap_size=length;
 for(i=length/2;i>=1;i--)
 {
  min_heaplfy(a,i);
 }
}

void heapsort(int *a)
{//堆的递减排序
 int i=0;
 build_min_heap(a);
 for(i=length;i>=2;i--)
 {
  swap(&a[1],&a[i]);
  heap_size=heap_size-1;
  min_heaplfy(a,1);
 }
}

int minimum(int *a)
{//return the min element
 return a[1];
}

int heap_extract_min(int *a)
{//去掉并返回A中具有最小关键字的元素
 int min=0;
 if(heap_size<1)
  printf("heap underflow!/n");
    min=a[1];
 a[1]= a[heap_size];
 heap_size-=1;
 min_heaplfy(a,1);
 return min;
}

void heap_decrease_key(int *a,int i,int key)
{//将元素I的key的值减少到key
 if(key>a[i])
  printf("new key is bigger than current key");
 a[i]=key;
 while( i>1 && a[PARENT(i)]> a[i] )
 {
  swap(&a[i], &a[PARENT(i)]);
  i=PARENT(i);
 }
}

void min_heap_insert(int *a, int key)
{
 heap_size=heap_size+1;
 a[heap_size]=INT_MAX;
 heap_decrease_key(a,heap_size,key);
}

 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值