标签:
#define MAX_HEAP_LEN 100 static int heap[MAX_HEAP_LEN]; static int heap_size = 0; ///堆中的元素个数 static void swap (int *a,int *b) { int temp=*a; *a=*b; *b=temp; } static void percolate_up(int i) { ///向上调整 if(i==0) return ; ///节点i已经是根节点了 int done=0; while((i!=0)&&(!done)) { if(heap[i]>heap[(i-1)/2]) { swap(&heap[i],&heap[(i-1)/2]); } else { done =1; } i=(i-1)/2; } } static void percolate_down(int i) { ///向下调整 if(2*i+1>heap_size) return ; ///节点i是叶子节点 int done=0; while((2*i+1<heap_size)&&(!done)) { i=i*2+1; ///跳转到左孩子 if((i+1<heap_size)&&(heap[i+1]>heap[i])) { ///在这两个孩子中找到较大者 i++; } if(heap[(i-1)/2]<heap[i]) { swap(&heap[(i-1)/2],&heap[i]); } else { done = 1; } } } static void delete (int i) { int last = heap[heap_size-1]; ///获取最后一个 heap_size--; ///收缩堆 if(i==heap_size) return ; heap[i]=last; ///用最后的节点覆盖当前的 percolate_down(i); } int delete_max() { int ret = heap[0]; delete(0); return ret; } void insert (int new_data) { if(heap_size>=MAX_HEAP_LEN) return; heap_size++; heap[heap_size-1]=new_data; percolate_up(heap_size-1); } void build () { ///建堆算法 for(int i=heap_size/2; i>0; i--) percolate_down(i); }
标签:
原文地址:http://www.cnblogs.com/TreeDream/p/5483204.html