数据结构之堆的实现

  堆:孩子都比父亲大,或者孩子都比父亲小



#ifndef _HEAP_H_
#define _HEAP_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 *this file is about heap of c-style,and i will offer the interface of push/pop/top/size
 *but,the program is c-style not cpp-style.you can transfer this program to cpp-style.and
 *use template class to implement the heap.
 *you can copy/re-write/sell/etc this program by any you can think but no need to let me know
 *and if you print the name of me at the copy-file of yours.or just copy this comment to your
 *program's proper position.i will cry by your merciful.
 *by hujian. 2016/5/24 nankai university
*/


#define HEAP_MAX_SIZE 1024*100 //you can change the size here

//this is the heap array.and the type of heap'e element is int!
static int heap[HEAP_MAX_SIZE];

//the current size of this heap.i will give the interface  to invoke the value
static int size_=0;

//get size
int size(){return size_;}

//get the top,and just return the minimum element but no remove it from heal
//if you want to get the minimum element with remove it,just use the pop.
int top(){return heap[0];}

//push an element to heap
void push(int v)
{
   //the index of self.
   int i=size_++;
   while(i>0){
      //get the parent's index
      int p=(i-1)/2;
      //adjust the heap
      if(heap[p]<=v) break;
      heap[i]=heap[p];
      i=p;
   }
   heap[i]=v;
}

//pop an element,return the top element and reomve it from heap
int pop()
{
   int res=heap[0];
   int x=heap[--size_];
   
   int i=0;
   while(i*2+1<size_){
       //get the min(lch,rch),and the a is min-res
       int a=i*2+1;
       if(a+1<size_&&heap[a+1]<heap[a]) a=a+1;
       
       if(heap[a]>=x) break;
       heap[i]=heap[a];
       i=a;
   }
   heap[i]=x;
  return res;
}

//create the heap
//@data:the array of data
//@len:the len of the data array
void create_heap(int *data,int len)
{
   //init the heap
   memset(heap,0,sizeof(heap));
   int i;
   for(i=0;i<len;i++){
      push(data[i]);
   }
   return;
}


//test
int main(int argc,char** argv)
{
   int *data;
   data=(int*)malloc(sizeof(int)*argc);
   if(NULL==data){
       printf("Malloc error! memory out!\n");
       return -1;
   }
   //get the data
   memset(data,0,sizeof(data));
   int i;
   for(i=0;i<argc-1;i++){
      data[i]=atoi(argv[i+1]);
   }
   
   //create the heap
   create_heap(data,argc-1);
   
   printf("The size of heap is:%d,the top element is:%d\n",size(),top());
   
   //show the heap
   while(size()>0){
     printf("[%d] ",pop());
   }
   printf("\n");
}


#endif //end of heap header
///<2016/5/24 hujian nankai edu> 


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值