C++ 构建最小堆、最大堆
生活随笔
收集整理的這篇文章主要介紹了
C++ 构建最小堆、最大堆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
- 堆的屬性
堆只是一種數據的組織形式,存儲結構可以用數組,在構建堆的過程中,可以使用完全二叉樹的性質求父子節點的下標。
父節點的下標 = 向下取整 ( (子節點下標 - 1) / 2) #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> void minheap(); void maxheap(); using namespace std; int arr[8] = { 53,17,78,9,45,65,87,23 }; int *a = new int[8];//保存小根堆 int index = 0; int main() {minheap();cout << "建立的最小堆為:" << endl;for (int i = 0; i < 8; i++){cout << a[i] <<" ";}system("pause"); }void maxheap() {while(index < 8) {a[index] = arr[index];if (index != 0) {int son_index = index;int par_index = floor((son_index - 1) / 2);while(a[par_index] < a[son_index]) {int tmp = a[par_index];a[par_index] = a[son_index];a[son_index] = tmp;son_index = par_index;par_index = floor((par_index - 1) / 2);}}index ++;} } void minheap() {while (index < 8) {a[index] = arr[index];if (index != 0) {int son_index = index;int par_index = floor((son_index - 1) / 2);while (a[par_index] > a[son_index]) {//小根堆:父節點大的話需要交換int temp = a[par_index];//交換a[par_index] = a[son_index];a[son_index] = temp;son_index = par_index;//迭代看之前的是否需要調整par_index = floor((son_index - 1) / 2);}}index ++;} }總結
以上是生活随笔為你收集整理的C++ 构建最小堆、最大堆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 阿里巴巴国际站多少钱啊?
- 下一篇: 数组中第K个最大元素