二叉堆的C語言實現

                                    二叉堆的C語言實現              
二叉堆的實現數據結構中如何使用,我任務主要是在操作系統中的任務優先級調度問題,當然也可以用於實現堆排序問題,比如找出數組中的第K個最小值問題,採用二叉堆能夠快速的實現,今天我就採用C語言實現了一個簡單的二叉堆操作,完成這些數據結構我並不知道能幹什麼,我就當自己在練習C語言的功底吧。逐步完成自己的代碼,希望自己在知識的理解力上有一定的提高。
 
二叉堆是非常有特點的數據結構,可以採用簡單的數組就能實現,當然鏈表的實現也是沒有問題的,畢竟是一個二叉樹問題,當然可以採用鏈表實現。採用數組實現時,可以找到兩個特別明顯的規律:
 
左兒子:L_Son = Parent * 2;
右兒子:R_Son = Parent * 2 + 1;
 
二叉堆是一顆完全填滿的樹,可能例外的是在底層,底層上的元素是從左到右填入,當然二叉堆可以是基於大值的排序,也可以是基於小值的排列形式,本文采用簡單的基於小值的形式。主要完成的操作:1、最小值的刪除操作,該操作會刪除根節點,然後提升兒子節點來代替根節點,具體的實現過程中通過提升左右兒子中較小的作爲父結點,依此提升直到到達最底層,這種實現方式叫做下慮法。2、數據的插入操作,插入操作可能會破壞二叉堆的結構,一般在最底層創建一個空穴,然後比較插入值與空穴父結點的值,如果大於父結點的值,那麼直接插入到空穴中,如果小於父結點,則將父結點的值插入到剛創建的空穴中,在父結點所在位置上形成新的父結點,這時候再和父結點的父結點比較,具體操作如上所述,直到找到具體的插入地址。當結點個數爲偶數時,在刪除操作中需要注意節點是否有右兒子的情況。具體的可以參考代碼中的說明。
 
具體的實現如下:
結構體:

點擊(此處)摺疊或打開

  1. #ifndef __BINARYHEAP_H_H_
  2. #define __BINARYHEAP_H_H_

  3. #include <stdlib.h>
  4. #include <assert.h>

  5. #define bool int
  6. #define true 1
  7. #define false 0

  8. /*打算採用數組的方式實現完全二叉堆*/
  9. typedef struct _binaryheap
  10. {
  11.         /*因爲需要動態擴展,
  12.         *採用靜態數組不方便*/
  13.         int * parray;
  14.         /*目前存在的結點*/
  15.         int currentSize;
  16.         /*樹的實際容量*/
  17.         int capacity;
  18. }BinaryHeap_t, *BinaryHeap_handle_t;

  19. #ifdef __cplusplus
  20. extern "C"
  21. {
  22. #endif

  23. bool init_BinaryHeap(BinaryHeap_handle_t heap, int capacity);
  24. bool alloc_BinaryHeap(BinaryHeap_handle_t *heap, int capacity);
  25. void delete_BinaryHeap(BinaryHeap_handle_t heap);
  26. void free_BinaryHeap(BinaryHeap_handle_t *heap);

  27. bool insert(BinaryHeap_handle_t heap,int value);
  28. int deleteMin(BinaryHeap_handle_t heap);
  29. bool isEmpty(BinaryHeap_handle_t heap);

  30. #ifdef __cplusplus
  31. }
  32. #endif

  33. #endif
實現的接口函數如下:

點擊(此處)摺疊或打開

  1. #include "binaryheap.h"

  2. bool isEmpty(BinaryHeap_handle_t heap)
  3. {
  4.         assert(heap != NULL);
  5.         return heap->currentSize == 0;
  6. }

  7. bool init_BinaryHeap(BinaryHeap_handle_t heap, int capacity)
  8. {
  9.         int *parray = NULL;

  10.         if(heap == NULL)
  11.                 return false;
  12.     
  13.         parray = (int *)calloc(capacity+1,sizeof(int));
  14.         if(parray == NULL)
  15.                 return false; 
  16.     
  17.         heap->parray = parray;
  18.         heap->capacity = capacity;
  19.         heap->currentSize = 0;

  20.         return true;
  21. }

  22. void delete_BinaryHeap(BinaryHeap_handle_t heap)
  23. {
  24.         assert(heap != NULL && heap->parray != NULL);

  25.         heap->capacity = 0;
  26.         heap->currentSize = 0;

  27.         free(heap->parray);
  28.         heap->parray = NULL;
  29. }

  30. void free_BinaryHeap(BinaryHeap_handle_t *heap)
  31. {
  32.         assert(*heap != NULL);

  33.         (*heap)->capacity = 0;
  34.         (*heap)->currentSize = 0;

  35.         free((*heap)->parray);
  36.         (*heap)->parray = NULL;

  37.         free(*heap);
  38.         *heap = NULL;
  39. }

  40. bool alloc_BinaryHeap(BinaryHeap_handle_t *heap, int capacity)
  41. {
  42.         int *parray = NULL;

  43.         if(*heap != NULL)
  44.                 return false;

  45.         *heap = (int *)calloc(1, sizeof(BinaryHeap_t));
  46.         if(*heap == NULL)
  47.                 return false;

  48.         /*其中的1,主要是爲了使得數組從下標1開始計算*/
  49.         parray =(int *)calloc(capacity + 1, sizeof(int));
  50.         if(parray == NULL)
  51.                 return false;

  52.         (*heap)->parray = parray;
  53.         (*heap)->capacity = capacity;
  54.         (*heap)->currentSize = 0;

  55.         return true;
  56. }

  57. /**************************************************
  58.  * 採用上慮法實現數據的插入操作
  59.  * 上慮法的實現方式比較簡單,首先創建一個空節點
  60.  * 然後將需要插入的值與當前空穴的父結點進行比較
  61.  * 如果大於父結點,直接插入空穴中
  62.  * 如果小於父結點的值,則將父結點的值下拉到空穴中
  63.  * 之前父結點的位置就是空穴,接着與上層比較
  64.  * 直到找到父結點大於當前插入值的情況
  65.  **************************************************/
  66. bool insert(BinaryHeap_handle_t heap, int value)
  67. {
  68.         int index = 0;

  69.         if(heap == NULL || heap->parray == NULL)
  70.                 return false;

  71.         /*得到一個新的空穴下標*/
  72.         index = ++heap->currentSize;
  73.         /*條件是不是第一個下標和插入值比對應父結點小*/
  74.         while(index > 1 && value < heap->parray[index/2])
  75.         {
  76.                 /*將父結點保存到當前結點處*/
  77.                 heap->parray[index] = heap->parray[index/2];
  78.                 /*得到父結點的空穴位置*/
  79.                 index /= 2;
  80.         }
  81.         /*將插入的值保存到剩餘的空穴中*/
  82.         heap->parray[index] = value;

  83.         return true;
  84. }

  85. /***********************************************************
  86.  * 下慮法實現數據的重排序操作
  87.  * 實現的方式,將子結點的兩個兒子進行比較,將小的提升
  88.  * 需要注意的是如何讓判斷節點是否一定存在右兒子
  89.  * 實現的方式主要是利用了二叉堆的特性:
  90.  * 2*pare = L_child
  91.  * 2*pare + 1 = R_child; 
  92.  ***********************************************************/
  93. static void presort_BinaryHeap(BinaryHeap_handle_t heap,int hole)
  94. {
  95.         /*這是二叉堆的特性*/
  96.         int child = hole * 2;
  97.         /*保存當前數據操作*/
  98.         int tmp = 0;

  99.         assert(heap != NULL && heap->parray != NULL);

  100.         tmp = heap->parray[hole];
  101.         /*hold * 2 <= heap->currentSize 判斷了當前結點是否爲最低層*/
  102.         for(; hole * 2 <= heap->currentSize; hole = child)
  103.         {
  104.                 child = hole * 2;

  105.                 /*******************************
  106.                 *這句代碼解決是否存在右結點的問題
  107.                 *並確定了那個子結點提升的問題
  108.                 *******************************/
  109.                 if((child != heap->currentSize)
  110.                         && (heap->parray[child + 1] < heap->parray[child]))
  111.                         child ++;

  112.                 if(heap->parray[child] < tmp)
  113.                 {
  114.                         /*將子結點提升爲父結點*/
  115.                        heap->parray[hole] = heap->parray[child];
  116.                 }
  117.         }
  118.         /*到達了最低的層,也就是樹葉*/
  119.         heap->parray[hole] = tmp;
  120. }

  121. /*實現數據的下慮法實現數據的刪除操作*/
  122. int deleteMin(BinaryHeap_handle_t heap)
  123. {
  124.         int ret = 0;
  125.         int index = 0;

  126.         assert(!isEmpty(heap));
  127.         /*需要返回的值*/
  128.         ret = heap->parray[1];

  129.         /*將最後需要釋放內存空間的值保存到第一個內存空間中*/
  130.         heap->parray[1] = heap->parray[heap->currentSize --];
  131.         /*從表頭開始將新的二叉樹進行重新排序*/
  132.         presort_BinaryHeap(heap, 1);

  133.         return ret;
  134. }
測試代碼:

點擊(此處)摺疊或打開

  1. #include "binaryheap.h"
  2. #include <stdio.h>
  3. #include <time.h>

  4. void print_binaryheap(BinaryHeap_handle_t heap)
  5. {
  6.         int i = 0;

  7.         assert(heap != NULL && heap->parray != NULL);

  8.         for(= 1; i <= heap->currentSize; ++ i)
  9.         {
  10.                 if(%6)
  11.                         printf("%d\t",heap->parray[i]);
  12.                 else
  13.                         printf("\n%d\t",heap->parray[i]);
  14.         }
  15.         printf("\n");
  16. }

  17. int main()
  18. {
  19.         int i = 0;
  20.         int value = 0;

  21.         srand((int)time(0));
  22.         printf("********Test Binaryheap**************\n");

  23.         BinaryHeap_t bheap;
  24.         BinaryHeap_handle_t *pheap = NULL;

  25.         printf("init and alloc test:\n");
  26.         if(init_BinaryHeap(&bheap,10))
  27.        {
  28.                 printf("init_BinaryHeap() successed!\n");
  29.         }
  30.         if (alloc_BinaryHeap(&pheap,15));
  31.         {
  32.                 printf("alloc_BInaryHeap() successed!\n");
  33.         }

  34.         printf("***insert test*****\n");
  35.         for(; i < 10; ++ i)
  36.         {
  37.                 if(!insert(&bheap,* i - rand()%20))
  38.                 {
  39.                         printf("i = %d:insert failed !!\n",i);
  40.                 }
  41.         }
  42.         for(= 0; i < 15; ++ i)
  43.         {
  44.                 if(!insert(pheap,* 8 - rand()%20))
  45.                 {
  46.                         printf("i = %d:insert failed!!\n",i);
  47.                 }
  48.         }

  49.         print_binaryheap(&bheap);
  50.         print_binaryheap(pheap);

  51.         printf("****deleteMin test****\n");
  52.         for(= 0; i < 5; ++ i)
  53.         {
  54.                 value = deleteMin(&bheap);
  55.                 printf("bheap deleted:%d\n",value);
  56.                 value = deleteMin(pheap);
  57.                 printf("pheap deleted:%d\n",value);
  58.         }
  59.         print_binaryheap(&bheap);
  60.         print_binaryheap(pheap);

  61.         printf("deleteMin test successed\n");

  62.         printf("****delete and free test:*******\n");
  63.         delete_BinaryHeap(&bheap);

  64.         printf("Is the bheap empty ? %s\n",
  65.                         isEmpty(&bheap)?"Yes":"No");

  66.         free_BinaryHeap(&pheap);

  67.         printf("*********Test successed!***********\n");
  68.         pheap = NULL;
  69.         return 0;
  70. }
測試結果:

點擊(此處)摺疊或打開

  1. [gong@Gong-Computer c_binaryheap]$ ./testbinaryheap
  2. ********Test Binaryheap**************
  3. init and alloc test:
  4. init_BinaryHeap() 
  5. alloc_BInaryHeap() 
  6. ***insert test*****
  7. -11    -9    -9    14    15    
  8. 10    21    23    40    26    
  9. -16    2    14    20    13    
  10. 21    33    49    61    67    76    
  11. 86    83    95    109    
  12. ****deleteMin test****
  13. bheap deleted:-11
  14. pheap deleted:-16
  15. bheap deleted:-9
  16. pheap deleted:2
  17. bheap deleted:-9
  18. pheap deleted:13
  19. bheap deleted:10
  20. pheap deleted:14
  21. bheap deleted:14
  22. pheap deleted:20
  23. 15    23    21    40    26    
  24. 21    49    21    61    67    
  25. 76    33    95    83    109    
  26. deleteMin test successed
  27. ****delete and free test:*******
  28. Is the bheap empty ? Yes
  29. *********Test

從上面的測試結果可知,基本上實現了二叉堆的基本插入、刪除操作。代碼的關鍵點在於刪除中的下慮和插入過程中的上慮操作。以及如何判斷代碼是否存在右兒子,如何充分運用二叉堆的特性。
發佈了34 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章