【手写系列】手写建堆

Posted on 2018-01-28 00:42  Unkn0wnnnnn  阅读(224)  评论(0)    收藏  举报

建堆过程其实也很简单,以堆的Heap/2开始进行一个子节点与左右节点的比较,建立大堆则根节点为最大,左子节点大于右子节点,小堆则反之。具体实现代码如下:

 1 void AdjustMaxHeap(int heap[],int RootIndex, int HeapLength){
 2     int LeftChildIndex=RootIndex*2;
 3     int RightChildIndex=LeftChildIndex+1;
 4     int MaxIndex=0;
 5     if(LeftChildIndex<HeapLength&&RightChildIndex<HeapLength){
 6         if(heap[LeftChildIndex]>heap[RightChildIndex]){
 7             if(heap[RootIndex]>heap[LeftChildIndex]){
 8                 MaxIndex=RootIndex;
 9             }
10             else{
11                 MaxIndex=LeftChildIndex;
12             }
13         }
14         else{
15             if(heap[RightChildIndex]>heap[RootIndex]){
16                 MaxIndex=RightChildIndex;
17             }
18             else{
19                 MaxIndex=RootIndex;
20             }
21         }
22     }
23     if(LeftChildIndex<HeapLength&&RightChildIndex>=HeapLength){
24         if(heap[LeftChildIndex]>heap[RootIndex]){
25             MaxIndex=LeftChildIndex;
26         }
27         else{
28             MaxIndex=RootIndex;
29         }
30     }
31     if (MaxIndex!=RootIndex){
32         int temp=heap[RootIndex];
33         heap[RootIndex]=heap[MaxIndex];
34         heap[MaxIndex]=heap[RootIndex];
35         AdjustMaxHeap(heap,MaxIndex,HeapLength);
36     }
37 }
38 void CreatMaxHeap(int heap[],int HeapLength)
39 {
40     for(int i =HeapLength/2;i>=1,i--){
41         AdjustMaxHeap(heap,i,HeapLength)
42     }
43 }

实现最小堆的过程则是针对判定条件进行改变即可。这里进行省略(其实就是太懒了)