数据结构之堆的实现
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>
相关文章推荐
- 冒泡排序及其改进
- 使用不完全填满数组的实现的循环FIFO(队列)
- Gson
- 串的模式匹配(BF算法,KMP算法)
- 绘图神器 —— Graphviz 绘制数据结构相关图形
- 数据结构和算法 – 7.散列和 Hashtable 类
- PHP数据结构:栈、队列、堆、固定数组
- OpenCV里IplImage数据结构中的width和widthStep
- 每天一点数据结构之二叉树非递归遍历
- Java千百问_06数据结构(022)_String在内存中如何存放
- <<数据结构和离散数学>>树的等价关系,集合论学习
- 数据结构之链表
- # 数据结构-顺序表和链式表
- java 链表数据结构实现
- 数据结构实验之栈五:下一较大值(一)
- 线段树 单点更新
- 数据结构之排序算法的稳定性
- 高级数据结构B树
- 图形的遍历方法之先深后广法
- 04-树5 Root of AVL Tree (25分)