堆及其操作

2021-09-27 12:30:27 字數 1611 閱讀 1236

堆及其操作

#include #include #include #define maxdata 1000  //該值根據具體情況定義為大於堆中所有可能元素的值

#define error -1 //錯誤標誌 應根據具體情況定義為堆中不可能出現的元素值

//堆的c語言描述

struct hnode

;struct hnode* creatheap(int maxsize)

//作用:判斷當前堆是否為空

bool isfull(struct hnode* h)

//作用:最大堆的插入操作

// 將元素x插入最大堆h,其中h->data[0]已經定義為哨兵

bool insert(struct hnode* h,int x)

i = ++h->size; //i指向插入後堆中最後乙個元素的位置

for ( ; h->data[i/2] < x ; i = i / 2)

h->data[i] = x;

return true;

}//判斷當前堆中元素是否為空

bool isempty(struct hnode* h)

//作用:從最大堆中取出鍵值最大的元素,並刪除乙個節點

int deletemax(struct hnode* h)

maxitem = h->data[1]; //取出根節點存放的最大值

x = h->data[h->size--]; //用最大堆中最後乙個元素從根節點開始向上過濾下層節點

//注意當前堆的規模要減小

for (parent = 1;parent * 2 <= h->size;parent = child)

if (x >= h->data[child])

else

}h->data[parent] = x;

return true;

}//作用:下濾 將h->data[p]為根的子堆調整為最大堆

void percdown(struct hnode* h,int p)

if (x >= h->data[child])

else

}h->data[parent] = x;

}//作用:最大堆的建立

//這裡假設所有h->size個元素已經存在與h->data中

void buildheap(struct hnode* h)

}void printheap(struct hnode* h)

}int main()

; for (int i = 1;i <= sizeof(a) / sizeof(a[0]);i++)

printf("構建堆:\n");

buildheap(heap);

printheap(heap);

printf("刪除元素後:\n");

deletemax(heap);

printheap(heap);

printf("插入元素後:\n");

insert(heap,58);

printheap(heap);

system("pause");

return 0;

}

堆及其應用

對於堆的資料結構的介紹,在網上搜了下,具體講的不是很多。發現比較好的一篇介紹堆的部落格是在此感謝他。通過對上面那篇部落格的學習,然後自己也去翻了下 演算法導論 裡面關於堆排序 heapsort 的介紹。這樣就對堆有了更加深刻的認識,在此,我結合自己的一點點理解,主要還是基於上面那篇部落格的內容 主要...

堆及其應用

應用1.優先順序佇列 優先順序佇列 是不同於先進先出佇列的另一種佇列。每次從佇列中取出的是具有最高優先權的元素。pragma once include include include include heap.h using namespace std template class priority...

初步了解二叉堆(二叉堆及其基本操作)

如圖,簡單來說,二叉堆是一棵滿足 堆性質 的完全二叉樹,樹上的每乙個節點都帶有乙個權值。若樹中任意的乙個節點的權值都小於等於其父節點的權值,則稱滿足該性質的完全二叉樹為大根堆 根權值最大 若樹中任意的乙個節點的權值都大於等於其父節點的權值,則稱滿足該性質的完全二叉樹為小根堆 根權值最小 二叉樹是一種...