二叉堆(Binary Heap)

看动画学算法之:二叉堆Binary Heap 我们坐在高高的谷堆旁边,听妈妈讲那过去的事情。听到了堆,我就想起了这首歌。 没错,今天我们要介绍一个堆,这个堆叫做二叉堆。 二叉树我们之前讲过了,就是每个节点最多有两个子节点的树叫做二叉树。而二叉堆Binary Heap是一种特殊的二叉树。 阅读详情

堆是完全二叉树,我们使用下标从1开始的数组来表示这颗树,1代表根节点,对于每个节点 i i i,它的左孩子为 i × 2 i \times 2 i×2,右孩子为 i × 2 + 1 i\times 2 + 1 i×2+1,父亲节点为 i / 2 i/2 i/2。最大堆和最小堆是二叉堆的形式,按照最大元素位于根节点排列的二叉堆被称为最大堆,同理按照最小元素位于根节点排列的二叉堆被称为最小堆。

二叉堆中主要的操作有查询、删除、插入,对于破坏堆性质的节点,可以使用上浮和下沉操作进行调整。

下面的操作以最大堆为例。

上浮

不断与父节点比较,如果比父节点大就与之交换,直到不大于父节点或成为根节点为止。

void up(int p) {
    for (int i = p; i > 1 && heap[i] > heap[i / 2]; i = i / 2) {
        swap(i, i / 2);
    }
}

void swap(int p1, int p2) {
    heap[p1] += heap[p2];
    heap[p2] = heap[p1] - heap[p2];
    heap[p1] = heap[p1] - heap[p2];
}

下沉

不断与较大的子节点比较,如果比它小就与之交换,直到不小于任何子节点或成为叶子节点为止。

void down(int p) {
    for (int i = p, j = son(i); j < heap.length && heap[j] > heap[i]; i = j, j = son(i)) {
        swap(i, j);
    }
}

int son(int p) {
    return 2 * p + ((2 * p + 1 <= heap.length && heap[2 * p + 1] > heap[p]) ? 1 : 0);
}

插入

直接在数组尾部插入值,然后上浮即可。

void push(int v) {
    heap[++size] = v;
    up(size);
}

删除

可以将根节点与最后一个节点交换,使size减1,然后根节点下沉。

void pop() {
    swap(1, size--);
    down(1);
}

查询

直接返回根节点即可。

int top() {
    return heap[1];
}

代码

完整的代码为:

public class Template {

    int size;
    int[] heap;

    public Template(int _size) {
        heap = new int[_size + 1];
        size = 0;
    }

    void up(int p) {
        for (int i = p; i > 1 && heap[i] > heap[i / 2]; i = i / 2) {
            swap(i, i / 2);
        }
    }

    void swap(int p1, int p2) {
        heap[p1] += heap[p2];
        heap[p2] = heap[p1] - heap[p2];
        heap[p1] = heap[p1] - heap[p2];
    }

    void down(int p) {
        for (int i = p, j = son(i); j < size && heap[j] > heap[i]; i = j, j = son(i)) {
            swap(i, j);
        }
    }

    int son(int p) {
        return 2 * p + ((2 * p + 1 <= size && heap[2 * p + 1] > heap[p]) ? 1 : 0);
    }

    void push(int v) {
        if (size >= heap.length - 1) return;
        heap[++size] = v;
        up(size);
    }

    void pop() {
        if (size > 0) return;
        swap(1, size--);
        down(1);
    }

    int top() {
        return heap[1];
    }

    public static void main(String[] args) {
        Template template = new Template(2);
        template.push(2);
        template.push(5);
        template.pop();
        template.pop();
    }
}

参考文献:

  1. 算法学习笔记(47): 二叉堆
几种堆(BinaryHeap, FibHeap, PairHeap)在Dijkstra算法上的效率试 立即下载

相关推荐

关于Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error 解决办法

Win11安装Ubuntu子系统报错:WslRegisterDistribution failed with error

qq_51908382的博客 3万+

二叉堆 Binary Heap

二叉堆 Binary HeapBinary Heap的基本概念Binary Heap的核心原理siftUpsiftDownBinary Heap的基本方法HeapifyPushPopBinary Heap的时间复杂度Binary Heap的实现Heap InterfaceHeap AbstractMax HeapMin Heap Binary Heap的基本概念 Heap是一个完全二叉树 (Complete Tree) 根节点最大是Max Heap, 根节点最小是Min Heap Max Hea

HelloWorld 1243

版电力系统故障录波_故障录波识图与典型故障波形分析

1、设置故障录波的目的故障录波装置是对电力系统运行状况进行监控的一种自动化设备。系统正常运行时,录波装置不启动录波,当系统发生故障时,通过启动录波装置迅速启动录波器录波,直接记录反应故障装置安装处系统故障的电气量。2、故障录波的作用(1)正确评价继电保护和自动装置的工作。(2)正确分析事故的原因并研究防止对侧。(3)发现继电保护和自动装置缺陷。(4)发现一次设备缺陷,及时消除隐患。(5)帮助寻找故...

weixin_42495661的博客 1万+

【数据结构与算法学习笔记-Binary Heap优先队列和二叉堆】

本文为学习笔记,感兴趣的读者可在MOOC中搜索《数据结构与算法Python版》或阅读《数据结构(C语言版)》(严蔚敏)。 本文包括优先队列的介绍,从树到完全二叉树到二叉堆的关系,二叉堆的实现(Python和JavaScript),相关复杂度的计算。

floating_heart的博客 746

VSCODE编辑+EIDE插件调试+STM8_Debug插件调试+IAR_STM8工具链编译开发项目

1. 安装 在VS CODE安装EIDE、STM8-Debug插件 2. 使用 EIDE 创建一个 8/16 Bit MCU 项目 新建虚拟文件夹,把工程外部的文件添加进虚拟文件夹,实现工程和源文件之间的关系,而不用实际把源文件复制到工程目录下。 EIDE工程和源文件实现分开放置,EIDE(EIDE工程)、EWSTM8(IAR STM8工程)、Project(ST Visual Develop工程) 选择工具链 烧录工具选择 头文件包含目录 添加宏定义 3. 编译 4. 使用STM8

TrueLink的博客 5500

数字后端实战指南 | Innovus Function ECO全流程解析(从LAB到Tapeout)

本文深入解析了在Cadence Innovus工具中进行Function ECO的全流程实战指南。从LAB环境搭建到Tapeout前的签核验证,详细拆解了Pre-mask与Post-mask ECO的核心步骤、关键命令(如ecoDesign)以及常见避坑方案。重点阐述了如何应对时序、DRC等挑战,并强调了备用单元管理与严格验证的重要性,是数字后端工程师提升综合能力的必备参考。

weixin_28452161的博客 639

[数据结构与算法]-二叉堆(binary heap)介绍及其实现(Java)

本文欢迎转载,转载前请联系作者。若未经允许转载,转载时请注明出处,谢谢! http://blog.youkuaiyun.com/colton_null 作者:喝酒不骑马 Colton_Null from 优快云 一.什么是二叉堆? 二叉堆(binary heap)是一种通常用于实现优先队列的数据结构。要想知道二叉堆是什么东西,得从两方面介绍它:结构性和堆序性。 1.结构性 二叉堆是一颗除底层...

因特马 4644

Blender点云渲染实战:用Geometry Nodes快速搞定论文配图(附Cycles渲染技巧)

本文详细介绍了如何利用Blender的Geometry Nodes系统,高效地将三维点云数据转化为高质量的科研论文配图。通过实战步骤,从数据导入、节点化几何处理、材质赋予到Cycles渲染引擎的优化设置,手把手教你制作出专业、美观的可视化图像,助力科研成果展示。

hp777的博客 265

STL源码剖析笔记——Binary Heap、priority_queue

STL源码剖析笔记——Binary Heap、priority_queue

weixin_48956191的博客 1449

使用TBtools进行物种间共线性分析

Sequence Toolkit ---Fasta Tools ----ID Prefix (fasta文件)

sunny_dayone的博客 8743

常用元器件使用方法13:物理层接口芯片DP83848的使用方法

介绍: DP83848是以太网物理层接口芯片,具有多种型号,从便于焊接角度考虑LQFP-48封装较为合适,采用LQFP-48封装的芯片,有2种型号,分别为DP83848I和DP83848C,如下图所示。 其主要区别是使用温度不同,如下图所示。 这2种芯片芯片网上均有销售,按理说DP83848C价格应该更加便宜,实际不然,DP83848I的价格低于DP83848C,考虑或与芯片的出货量...

snmplink的博客 1万+

Binary Heap(二叉堆)

Binary Heap(二叉堆) 在计算机科学中,二叉堆是二叉树形状的堆结构。二叉堆是最常见的实现优先级队列的方法,它与优先级队列紧密相连,一起应用到诸多地方,在很多主流语言的标准算法库中都能看到它们的身影。同时它也是很多算法中需要用到的底层数据结构,能够快速地掌握这些已有的标准库和类,能够很高效地实现诸多算法。

chouisbo的博客 1879

【DEIM创新改进】全网独家创新、注意力改进篇 | AAAI 2026 | DEIM 引入轻量级群体注意力(LWGA)模块,可以显著提高其多尺度物体检测能力,特别是在小物体和复杂背景下的表现

本文提出了一种改进的DEIM网络模型,通过引入轻量级LWGA模块显著提升了多尺度物体检测性能。LWGA模块采用局部和全局注意力机制,有效提升了小物体和复杂背景下的识别能力,同时保持低计算成本。该模块通过分割输入特征图并应用多种注意力机制(GPA、RLA、SMA、SGA)进行特征提取和融合,优化了多尺度物体的特征表示。实验表明,改进后的DEIM模型在遥感图像处理等任务中表现出色,在12个数据集上实现了性能与计算效率的最佳平衡,为资源受限设备提供了高效的解决方案。

Ai缝合怪、助力小伙伴高效发论文 272

二叉堆(Binary Heap)

Binary Heap: 一个二叉堆(Binary Heap)是具有下面一些属性的二叉树: 1)是一个完全二叉树,即:除了叶子节点以外的其他节点全部有左右子树,并且最后一层的叶子节点按照从左到右填充。 2) 一个二叉堆可以是最大堆或者最小堆。 在最大堆中,根节点的值最大; 在最小堆中,根节点的值最小; 3) 所有子树符合性质2)最小二叉堆实例 10

hit_ynsun的博客 1118

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

二叉堆(binary heap)

前言 计算机两大基础:算法,数据机构。说到数据结构 ,必然就要提到堆栈。下面就来看看堆是个什么玩意儿。 二叉堆 二叉堆就是二叉树(又叫优先队列priority-queue),完全的二叉树中每一个父节点下有两个子节点。今天我们以max_heap为例,就是传说中的最大堆,即每一个父节点都要比自己的两个子节点大,根节点最大,它大于整个二叉堆中的所有节点值。 我们用一个vector来表示二叉堆...

qq_39747794的博客 643

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Python实现二叉堆-Binary Heap

本篇文章将简要解释什么是二叉堆以及二叉堆的Python实现什么是二叉堆(binary heap)实现思路(以最大堆为例)通过上浮操作来向堆中新增元素通过下沉操作来取出堆中元素数据结构设计&封装实现 什么是二叉堆(binary heap) 二叉堆是一种满足特殊性质的二叉树。具有以下性质: 二叉堆是一颗完全二叉树(除叶子节点以外其余节点的左右孩子都不为空) 所有节点的值都大于等于(最大堆)孩...

baidu_36146918的博客 1348

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

二叉堆(Binary_Heap)

二叉堆满足其结构性,和堆序性。结构性:要求为完全二叉树,即除树的最底层外,树被完全填满,且底层的元素从左向右填充。堆序性:即在堆中要求,对任意元素X,X的父节点的关键字小等于X的关键字,如此得到最小堆。同理可得最大堆。 由于堆序性,因此二叉堆也常称为实现优先队列(Priority Queue)。 在对二叉堆进行操作时需要始终保持其结构性和堆序性。可用数组来实现二叉堆。数组中的元素关系为:i位置上的节点,其左儿子在2i上,右节点在2i+1上,父节点在i/2(取整)上。用数组代替树结构,从而不用包含指针操作

艰难困苦如同欢乐,终将成为人生最后的财富 1022

Binary Heap 二叉堆 (二)

二叉堆

分享我的点点滴滴,在成长路上与你同行! 664

【学习笔记】堆Heap和 二叉堆 Binary Heap

1.堆 Heap 定义:可以迅速找到一堆数中的最大值或者最小值的数据结构。 应用场景:经常是一个数一个数的过来,比如找最大值或者找最小值 分类:堆本身是一个抽象的数据结构,根据实现形式,将其分为二叉堆、斐波那契堆等。 P.S: 二叉堆是堆(优先队列 priority_queue) 的一种常见且简单的实现,但是并不是最优的实现形式,但是在面试的时候以及教科书上出现比较多。真正在工程中使用的是 严格斐波那契堆等性能优异的堆,面试的时候知道有这么一种堆就行,暂时没必要知道怎么实现的。 参考 将根节点最大的堆叫做

KaelCui的博客 449

二叉堆(Binary heap)

Binary heap There are several types of heaps, but in the current article we are going to discuss the binary heap. For short, let's call it just "heap". It is used to implement priority queue ADT 

bdss58的专栏 2686

数据结构之Binary Heap(二叉堆)

数据结构之Binary Heap(二叉堆)1.Binary Heap的定义 二叉堆是一种特殊的堆,二叉堆是完全二元树(二叉树)或者是近似完全二元树(二叉树)。二叉堆有两种:最大堆和最小堆。最大堆:父结点的键值总是大于或等于任何一个子节点的键值;最小堆:父结点的键值总是小于或等于任何一个子节点的键值。二叉堆一般用数组来表示。

Rosun 6621

二叉堆-Binary heap

基本思想 (二叉)堆的定义 n个关键字序列k1,k2,…,kn称为堆,当且仅当该序列满足如下性质之一(简称堆性质):ki≤k2i且ki≤k2i+1 或 ki≥k2i且ki≥k2i+1(1≤i≤FLOOR(n/2)) 若将此序列所存储的向量R[1..n]看做是一棵完全二叉树的存储结构,则堆实质上是满足如下性质的完全二叉树:树中任一非叶结点的关键字均不大于(或不小于)其左右孩子(若 存在)结点的关键字

BrokenIceCrystal的博客 1344
上一篇: 单调栈(Monotonic Stack)
下一篇: 二叉搜索树(Binary Search Tree)
小菜2小白
博客等级 码龄4年 4粉丝 25原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值