C++ 构建最小堆、最大堆

  • 堆的属性
  1. 完全二叉树
  2. 每个节点的值都大于(最大堆)或都小于(最小堆)子节点的值

堆只是一种数据的组织形式,存储结构可以用数组,在构建堆的过程中,可以使用完全二叉树的性质求父子节点的下标。

父节点的下标 = 向下取整 ( (子节点下标 - 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 ++;
  }
}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值