最大堆(又叫大根堆、大顶堆)和最小堆是二叉堆的两种形式,一类很重要的数据结构,如用于堆排序等。
最小堆:根结点的键值是所有堆结点键值中最小者,且每个结点的值都比其孩子的值小。
最大堆:根结点的键值是所有堆结点键值中最大者,且每个结点的值都比其孩子的值大。
下面以大根堆为例,来说明其入堆和出堆的操作:
入堆,插入:向上渗透(先是插入堆的最后位置,然后按最大堆的规则调整到适当位置);
出堆,删除:向下渗透(第一个元素出堆,从第二层开始,较大的元素往上渗透,将最后一个元素赋值给倒数第二层上的当前元素。
代码:
<code>#include using namespace std; const int MAX = 55; typedef struct Heap { int sizeHeap; int* heapData; }HEAP,*LPHEAP; LPHEAP createHeap() { LPHEAP heap=(LPHEAP)malloc(sizeof(HEAP)); heap->sizeHeap=0; heap->heapData=(int*)malloc(sizeof(int)*MAX); return heap; } int size(LPHEAP heap) { return heap->sizeHeap; } int empty(LPHEAP heap) { return heap->sizeHeap==0; } void moveToCorrectPos(LPHEAP heap, int curPos)//向上渗透,curPos一般取最后一个元素的下标 { while(curPos>1) { int Max=heap->heapData[curPos]; int parentIndex=curPos/2; if(Max>heap->heapData[parentIndex]) { heap->heapData[curPos]=heap->heapData[parentIndex]; heap->heapData[parentIndex]=Max; curPos=parentIndex;//向上移动 } else { break; } } } void insertHeap(LPHEAP heap, int data) // 放到当前堆的最后面并按条件往上移 { ++heap->sizeHeap; heap->heapData[heap->sizeHeap]=data; moveToCorrectPos(heap,heap->sizeHeap); } int popHeap(LPHEAP heap) { int Max=heap->heapData[1]; int curPos=1; int childIndex=curPos*2; while(childIndex<=heap->sizeHeap) { int temp = heap->heapData[childIndex]; if(childIndex+1<=heap->sizeHeap && tempheapData[childIndex+1]) { temp=heap->heapData[++childIndex]; } heap->heapData[curPos]=temp; curPos=childIndex;//下移一层 childIndex*=2; } heap->heapData[curPos]=heap->heapData[heap->sizeHeap]; --heap->sizeHeap; return Max; } void main() { LPHEAP heap=createHeap(); for(int i=1;i<11;++i) { insertHeap(heap,i); } for(i=1;i<11;++i) { printf("%d\t",heap->heapData[i]); } printf("\n"); while(!empty(heap)) { printf("%d\t",popHeap(heap)); } system("pause"); } /* 10 9 6 7 8 2 5 1 4 3 10 9 8 7 6 5 4 3 2 1 *//<code>
在STL算法库中,有一簇函数专门用来将某一个序列容器调整为大堆或小堆:
(以下函数参数_Compare,可以是less<>(),与大顶堆相关;或者greater<>(),与小顶堆相关)
make_heap(_RAIter,_RAIter,_Compare): 生成大顶堆或小顶堆;
push_heap(_RAIter,_RAIter,_Compare) :如果有向堆(容器)中插入(.push_back())元素,需要使用此函数来调整大堆或小堆;
pop_heap(_RAIter,_RAIter,_Compare) :将堆(容器)中的第一个元素与最后一个元素交换,除最后一个元素以外,前面的元素按大堆或小堆规则调整。由此,如果删除(.pop_back())最后一个元素,剩下的元素又是一个大堆或小堆。
具体细节见代码和注释:
<code>#include #include #include #include using namespace std; void printVector(vector vc) { copy(vc.begin(),vc.end(),ostream_iterator(cout," ")); cout
-End-