Heap Sort Algorithm

heap

A heap is a specialized tree-based data structure that satisfies the heap property. It’s commonly implemented as a binary tree, particularly an array-based representation, where the parent node’s value is either greater than or less than (depending on whether it’s a max heap or min heap) the values of its children.

Complete binary trees: A binary tree in which all levels are completely filled except the last one. And if the last level is filled partially, it should be filled from left to right.

Key Characteristics:

  1. Heap Property: There are two types of heaps based on the heap property:

    • Max Heap: Every parent node has a value greater than or equal to the values of its children. A max-heap supports O(log n) insertions, O(1) time lookup for the max element, and O(log n) deletion of the max element. Searching for arbitrary keys has O(n) time
    • Min Heap: Every parent node has a value less than or equal to the values of its children. it supports O(1) time lookups for the minimum element.
  2. Representation:

    • Array Representation: In many implementations, heaps are represented using arrays, where the relationship between parent and child nodes is determined by their indices within the array.
      the children of the node at index i are at indices 2i + 1 and 2i + 2
  3. Common Operations:

    • Insertion: Adding a new element while maintaining the heap property.
    • Deletion: Removing the root node (max or min) while maintaining the heap property.
    • Heapify: Ensuring that the heap property is maintained after insertion or deletion.

Types of Heaps:

  1. Binary Heap: The most common type of heap, where each parent node has at most two children. It’s efficient for priority queue implementations and is often used in algorithms like Heap Sort and Dijkstra’s shortest path algorithm.

  2. Fibonacci Heap: A more advanced heap data structure that has better amortized time complexity for some operations compared to binary heaps, especially in certain graph algorithms.

Heap Applications:

  • Priority Queues: Heaps are often used to implement priority queues due to their ability to efficiently retrieve and remove the maximum or minimum element.
  • Heap Sort: A sorting algorithm that uses a heap data structure to sort elements in-place.
  • Dijkstra’s Algorithm: Finds the shortest path in a graph using a priority queue implemented with a heap.

Example of a Max Heap (Array Representation):

Let’s consider a simple max heap:

               9
             /   \
            7     6
           / \   / 
          5   4 3  

The array representation of this heap would be [9, 7, 6, 5, 4, 3], where each index represents a node, and the relationship between parent and child nodes is maintained based on their indices.

Heaps are efficient data structures that facilitate operations requiring quick access to the maximum or minimum element, making them valuable in various algorithms and applications

Heap Sort Algorithm

To solve the problem follow the below idea:
First convert the array into heap data structure using heapify, then one by one delete the root node of the Max-heap and replace it with the last node in the heap and then heapify the root of the heap. Repeat this process until size of heap is greater than 1.

  1. Build a heap from the given input array.
  2. Repeat the following steps until the heap contains only one element:
    i. Swap the root element of the heap (which is the largest element) with the last element of the heap.
    ii. Remove the last element of the heap (which is now in the correct position).
    iii. Heapify the remaining elements of the heap.
  3. The sorted array is obtained by reversing the order of the elements in the input array.

https://www.geeksforgeeks.org/building-heap-from-array/
https://www.geeksforgeeks.org/heap-sort/

Building Heap from Array

Given an array of N elements. The task is to build a Binary Heap from the given array. The heap can be either Max Heap or Min Heap.

input: arr[] = {4, 10, 3, 5, 1}

       4
     /   \
   10     3
  /  \
5     1

Output: Corresponding Max-Heap:

       10
     /   \
    5     3
  /  \
4      1

Note:

  1. Root is at index 0 in array.
  2. Left child of i-th node is at (2*i +1)th index.
  3. Right child of i-th node is at (2*i + 2)th index.
  4. Parent of i-th node is at (i-1)/2 index.

Naive Approach: To solve the problem follow the below idea:

To build a Max-Heap from the above-given array elements, It can be clearly seen that the above complete binary tree formed does not follow the Heap property. So, the idea is to heapify the complete binary tree formed from the array in reverse level order following a top-down approach. That is first heapify, the last node in level order traversal of the tree, then heapify the second last node and so on.
要从上述给定的数组元素中建立最大堆,可以清楚地看到,上述形成的完整二叉树并不遵循堆属性。因此,我们的想法是按照自上而下的方法,将数组形成的完整二叉树按相反的层级顺序进行堆化。即首先堆化树中按层级顺序遍历的最后一个节点,然后堆化倒数第二个节点,以此类推。

Array = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}
Corresponding Complete Binary Tree is:

             1
          /     \
       3         5
    /    \      /   \
  4       6    13   10
 / \     / \    
9   8   15 17

The task to build a Max-Heap from above array.

Total Nodes = 11.
Last Non-leaf node index = (11/2) – 1 = 4.
Therefore, last non-leaf node = 6.

To build the heap, heapify only the nodes: [1, 3, 5, 4, 6] in reverse order.

Heapify 6: Swap 6 and 17.

             1
          /     \
       3         5
    /    \      /  \
  4       17  13   10
 / \     /  \  
9   8  15    6

Heapify 4: Swap 4 and 9.

             1
          /     \
       3         5
     /    \    /   \
   9      17   13   10
  / \    /  \   
 4   8  15   6

Heapify 5: Swap 13 and 5.

             1
          /     \
       3         13
    /    \      /  \
  9      17   5    10
 / \    /  \  
4   8  15   6

Heapify 3: First Swap 3 and 17, again swap 3 and 15.

             1
         /     \
      17         13
   /    \       /  \
  9      15    5   10
 / \    /  \
4   8  3    6

Heapify 1: First Swap 1 and 17, again swap 1 and 15, finally swap 1 and 6.

             17
          /      \
       15         13
     /    \      /  \
    9      6    5   10
   / \    /  \
  4   8  3    1

Below is the implementation of the above approach:

英语:

Last non-leaf node 最后一个非叶子节点
the second last nod 倒数第二个节点

https://qidawu.github.io/posts/data-structure-tree/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/254348.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

NSSCTF第16页(3)

[SWPUCTF 2023 秋季新生赛]ez_talk 上传一句话木马得到 抓包改文件类型 上传成功,只是倒序而已 得到flag [第五空间 2021]PNG图片转换器 这道题采用的是ruby语言,第一次听说 2021-第五空间智能安全大赛-PNG图片转换器 | 管道符与反引号的配合、open…

使用python实现链表

手写代码 class Node(object):def __init__(self, item):self.item itemself.next Noneclass LinkListFunction(object):"""此对象为Node对象的方法类"""def __init__(self):self.linklistlength 0 # 当前链表的长度def create_linklist_he…

C语言学习第二十六天(算法的时间复杂度和空间复杂度)

1、算法效率 衡量一个算法的好坏,是从时间和空间两个方面来衡量的,换句话说就是从时间复杂度和空间复杂度来衡量的 这里需要补充一点:时间复杂度是衡量一个算法的运行快慢,空间复杂度是主要衡量一个算法运行所需要的额外空间。 …

「Verilog学习笔记」交通灯

专栏前言 本专栏的内容主要是记录本人学习Verilog过程中的一些知识点,刷题网站用的是牛客网 timescale 1ns/1nsmodule triffic_light(input rst_n, //异位复位信号,低电平有效input clk, //时钟信号input pass_request,output wire[7:0]clock,output reg…

Shared Worker的快速理解与简单应用

SharedWorker 是 HTML5 中引入的一种 WebWorkers 类型,用于在浏览器中创建可在多个浏览器窗口或标签页之间共享的后台线程。Web Workers 是在主线程之外运行的脚本,允许执行一些耗时的任务而不会阻塞用户界面。 对 SharedWorker 的概念、理解和应用的简要…

2023第十七届中国品牌节,酷开科技荣获金谱奖!

11月18日,以“复苏与腾飞”为主题的2023第十七届中国品牌节,在杭州市云栖小镇国际会展中心盛大开幕。来自政界、商界、文化界等领域的6000余名嘉宾出席本次盛会,共同见证了民族品牌的崛起,全力奉献一场史无前例的“品牌人的亚运会…

Pikachu漏洞练习平台之暴力破解(基于burpsuite)

从来没有哪个时代的黑客像今天一样热衷于猜解密码 ---奥斯特洛夫斯基 Burte Force(暴力破解)概述 “暴力破解”是一攻击具手段,在web攻击中,一般会使用这种手段对应用系统的认证信息进行获取。 其过程就是使用大量的认证信息在认…

【操作系统】实验名称: 实验五 文件系统

实验目的: 1. 掌握文件系统的基本概念和工作机制 2. 掌握文件系统的主要数据结构的实现 3、掌握软件系统实现算法 实验内容: 设计并实现一个虚拟的一级(单用户)文件系统程序 提供以下操作 1、文件创建/删除接口命令 2、目录创建/删…

合并 K 个排序链表——Java解答

题目:合并 K 个排序链表 题目描述: 给你一个链表数组,每个链表都已经按升序排列。请你将所有链表合并到一个升序链表中,返回合并后的链表。 示例: 假设有以下三个链表: 1->4->5, 1->3->4,…

QUIC在零信任解决方案的落地实践

一 前言 ZTNA为以“网络为中心”的传统企业体系架构向以“身份为中心”的新型企业安全体系架构转变,提供解决方案。随着传统网络边界不断弱化,企业SaaS规模化日益增多,给终端安全访问接入创造了多元化的空间。其中BYOD办公方式尤为突出&#…

SpringBoot使用@DS配置 多数据源 【mybatisplus druid datasource mysql】

项目最近需要使用多数据源,不同的mapper分别读取不同的链接,本项目使用了mybatisplus druid 来配置多数据源,基于mysql数据库。 目录 1.引入依赖 ​2.配置文件 application.yaml 3.Mapper中使用DS切换数据源 4.使用DS的注意事项 1.引入依…

苹果忽略iPhone?2024可穿戴产品或成重心!

一代版本一代神,即便是强如iPhone也有着被忽视的一天,当然,这么说有些夸张。虽然iPhone永远都是苹果最重要的产品,但在明年,苹果的重心将偏向其他产品。 彭博社记者马克古曼(Mark Gurman)在新一…

如何确保对称密钥管理的存储安全?

确保对称密钥管理的存储安全是保障信息安全的重要一环。以下是一些建议,以确保对称密钥管理的存储安全: 使用安全存储设备:选择使用经过验证的安全存储设备来存储对称密钥。这些设备通常具有高度的物理安全性,可以防止未经授权的访…

使用Umi搭建React项目

环境准备 一、首先确保有 node环境,并确保 node 版本是 14 或以上。(推荐用 nvm 来管理 node 版本,windows 下推荐用 nvm-windows) nvm使用教程 二、然后需要包管理工具。node 默认包含 npm,但也可以选择其他方案&a…

eclipse-安装WindowBuilder,怎么安装

WindowBuilder是Eclipse的一个插件,可以帮助开发者使用Java Swing、JavaFX和SWT快速构建图形用户界面(GUI)。下面是WindowBuilder的安装步骤: 1. 打开Eclipse IDE(请确保已安装JDK)。 2. 点击“Help”菜单…

【MySQL】:表的删除和修改

表的删除和修改 一.update(修改)二.delete(删除)1.删除数据2.截断表 三.插入查询的数据四.聚合函数五.group by 句子的使用1.导入表2.进行操作 一.update(修改) 对查询到的结果进行列值更新 下面有一个表,接下来的操作都是对该表进行操作。 1.将孙悟空同学的数学成绩…

目标跟踪 MOT数据集和可视化

目录 MOT15数据集格式简介 gt可视化 本人修改的GT可视化代码: MOT15数据集格式简介 以下内容转自:【目标跟踪】MOT数据集GroundTruth可视化-腾讯云开发者社区-腾讯云 MOT15数据集下载:https://pan.baidu.com/s/1foGrBXvsanW8BI4eybqfWg?…

100GPTS计划-AI写诗PoetofAges

地址 https://chat.openai.com/g/g-Cd5daC0s5-poet-of-ages https://poe.com/PoetofAges 测试 创作一首春天诗歌 创作一首夏天诗歌 创作一首秋天诗歌 创作一首冬天诗歌 微调 诗歌风格 语气:古典 知识库

嵌入式Linux开发板硬件学习-基于cadence

嵌入式Linux开发板硬件学习-基于cadence 目录原理图网表输出功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants 创建一个自定义列表如何创…

本章主要介绍Spring Framework中用来处理URI的多种方式

1.使用 UriComponentsBuilder 构建URi 话不多说 直接上代码 UriComponents uriComponents UriComponentsBuilder.fromUriString("https://example.com/hotels/{hotel}").queryParam("q", "{q}").encode().build();URI uri uriComponents.exp…
最新文章