Today we will be reviewing the heap data structure. A heap is a tree-based data structure, which indicates a heap will have a root node and some child nodes. We usually work with the binary ...
Today we will be reviewing the heap data structure.
A heap is a tree-based data structure, which indicates a heap will have a root node and some child nodes. We usually work with the binary heap. A binary has a left child and a right child. The following image is an example of a heap data structure.
To insert a node into a heap, we use the push function, and to remove the root from the heap, we use the pop function. When a new node needs to be inserted, it is inserted at the end of the heap structure. When we pop from a heap structure, the root element is removed from the heap structure. Once the root is removed, restructure is necessary to preserve the structure of the heap.
If we want to represent our heap in form of an array, index ‘k’ will hold the root node, then its left child is stored at index ‘2k + 1’ and its right child at index ‘2k + 2’.
The above heap will be represented as follows:
Array representation of Heap
Based on our requirement, we can either have a min-heap or a max-heap.
What is the difference between min-heap and max-heap?
In min-heap, the root nodes will be smaller than the child nodes.
An example of min-heap is as follows:
In a max-heap, the root node will be greater than the child node.
An example of max-heap is as follows:
Why would we require a min-heap or a max-heap?
Sorting is one of the applications of the heap. When we create a min-heap or a max-heap, it is easy for us to arrange our elements in ascending or descending order.
What are the other applications of the heap?
Let us move into sorting.
To perform heapsort we need to follow 2 steps.
Guide to Python Programming Language
This article will explore how to generate QR code in Python and some useful creation features from pyqrcode library. QR codes recently became more popular than ever before, yet few people know that the first iterations of QR codes were created back in 1990s in Japan for the automotive industry.
Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?
Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.
Python Programming Tutorials For Beginners