您的位置:首页 > 理论基础 > 数据结构算法

数据结构之堆的实现

2016-05-24 12:26 459 查看
堆:孩子都比父亲大,或者孩子都比父亲小

#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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: