Insertion and Deletion in Heaps
Last Updated :
10 Oct, 2023
Deletion in Heap:
Given a Binary Heap and an element present in the given Heap. The task is to delete an element from this Heap.
The standard deletion operation on Heap is to delete the element present at the root node of the Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum element and if it is a Min heap, it will delete the minimum element.
Process of Deletion:
Since deleting an element at any intermediary position in the heap can be costly, so we can simply replace the element to be deleted by the last element and delete the last element of the Heap.
- Replace the root or element to be deleted by the last element.
- Delete the last element from the Heap.
- Since, the last element is now placed at the position of the root node. So, it may not follow the heap property. Therefore, heapify the last node placed at the position of root.
Illustration:
Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The element to be deleted is root, i.e. 10.
Process:
The last element is 4.
Step 1: Replace the last element with root, and delete it.
4
/ \
5 3
/
2
Step 2: Heapify root.
Final Heap:
5
/ \
4 3
/
2
Implementation:
C++
// C++ program for implement deletion in Heaps
#include <iostream>
using namespace std;
// To heapify a subtree rooted with node i which is
// an index of arr[] and n is the size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Function to delete the root from Heap
void deleteRoot(int arr[], int& n)
{
// Get the last element
int lastElement = arr[n - 1];
// Replace root with last element
arr[0] = lastElement;
// Decrease size of heap by 1
n = n - 1;
// heapify the root node
heapify(arr, n, 0);
}
/* A utility function to print array of size n */
void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver Code
int main()
{
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
int arr[] = { 10, 5, 3, 2, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
deleteRoot(arr, n);
printArray(arr, n);
return 0;
}
Java
// Java program for implement deletion in Heaps
public class deletionHeap {
// To heapify a subtree rooted with node i which is
// an index in arr[].Nn is size of heap
static void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Function to delete the root from Heap
static int deleteRoot(int arr[], int n)
{
// Get the last element
int lastElement = arr[n - 1];
// Replace root with first element
arr[0] = lastElement;
// Decrease size of heap by 1
n = n - 1;
// heapify the root node
heapify(arr, n, 0);
// return new size of Heap
return n;
}
/* A utility function to print array of size N */
static void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver Code
public static void main(String args[])
{
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
int arr[] = { 10, 5, 3, 2, 4 };
int n = arr.length;
n = deleteRoot(arr, n);
printArray(arr, n);
}
}
Python3
# Python 3 program for implement deletion in Heaps
# To heapify a subtree rooted with node i which is
# an index of arr[] and n is the size of heap
def heapify(arr, n, i):
largest = i #Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
#If left child is larger than root
if (l < n and arr[l] > arr[largest]):
largest = l
#If right child is larger than largest so far
if (r < n and arr[r] > arr[largest]):
largest = r
# If largest is not root
if (largest != i):
arr[i],arr[largest]=arr[largest],arr[i]
#Recursively heapify the affected sub-tree
heapify(arr, n, largest)
#Function to delete the root from Heap
def deleteRoot(arr):
global n
# Get the last element
lastElement = arr[n - 1]
# Replace root with last element
arr[0] = lastElement
# Decrease size of heap by 1
n = n - 1
# heapify the root node
heapify(arr, n, 0)
# A utility function to print array of size n
def printArray(arr, n):
for i in range(n):
print(arr[i],end=" ")
print()
# Driver Code
if __name__ == '__main__':
# Array representation of Max-Heap
# 10
# / \
# 5 3
# / \
# 2 4
arr = [ 10, 5, 3, 2, 4 ]
n = len(arr)
deleteRoot(arr)
printArray(arr, n)
# This code is contributed by Rajat Kumar.
C#
// C# program for implement deletion in Heaps
using System;
public class deletionHeap
{
// To heapify a subtree rooted with node i which is
// an index in arr[].Nn is size of heap
static void heapify(int []arr, int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Function to delete the root from Heap
static int deleteRoot(int []arr, int n)
{
// Get the last element
int lastElement = arr[n - 1];
// Replace root with first element
arr[0] = lastElement;
// Decrease size of heap by 1
n = n - 1;
// heapify the root node
heapify(arr, n, 0);
// return new size of Heap
return n;
}
/* A utility function to print array of size N */
static void printArray(int []arr, int n)
{
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver Code
public static void Main()
{
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
int []arr = { 10, 5, 3, 2, 4 };
int n = arr.Length;
n = deleteRoot(arr, n);
printArray(arr, n);
}
}
// This code is contributed by Ryuga
JavaScript
<script>
// Javascript program for implement deletion in Heaps
// To heapify a subtree rooted with node i which is
// an index in arr[].Nn is size of heap
function heapify(arr, n, i)
{
let largest = i; // Initialize largest as root
let l = 2 * i + 1; // left = 2*i + 1
let r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
let swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Function to delete the root from Heap
function deleteRoot(arr, n)
{
// Get the last element
let lastElement = arr[n - 1];
// Replace root with first element
arr[0] = lastElement;
// Decrease size of heap by 1
n = n - 1;
// heapify the root node
heapify(arr, n, 0);
// return new size of Heap
return n;
}
/* A utility function to print array of size N */
function printArray(arr, n)
{
for (let i = 0; i < n; ++i)
document.write(arr[i] + " ");
document.write("</br>");
}
let arr = [ 10, 5, 3, 2, 4 ];
let n = arr.length;
n = deleteRoot(arr, n);
printArray(arr, n);
// This code is contributed by divyeshrabdiya07.
</script>
Time complexity: O(logn) where n is no of elements in the heap
Auxiliary Space: O(n)
Insertion in Heaps:
The insertion operation is also similar to that of the deletion process.
Given a Binary Heap and a new element to be added to this Heap. The task is to insert the new element to the Heap maintaining the properties of Heap.
Process of Insertion: Elements can be inserted to the heap following a similar approach as discussed above for deletion. The idea is to:
- First increase the heap size by 1, so that it can store the new element.
- Insert the new element at the end of the Heap.
- This newly inserted element may distort the properties of Heap for its parents. So, in order to keep the properties of Heap, heapify this newly inserted element following a bottom-up approach.
Illustration:
Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The new element to be inserted is 15.
Process:
Step 1: Insert the new element at the end.
10
/ \
5 3
/ \ /
2 4 15
Step 2: Heapify the new element following bottom-up
approach.
-> 15 is more than its parent 3, swap them.
10
/ \
5 15
/ \ /
2 4 3
-> 15 is again more than its parent 10, swap them.
15
/ \
5 10
/ \ /
2 4 3
Therefore, the final heap after insertion is:
15
/ \
5 10
/ \ /
2 4 3
Implementation:
C++
// C++ program to insert new element to Heap
#include <iostream>
using namespace std;
#define MAX 1000 // Max size of Heap
// Function to heapify ith node in a Heap
// of size n following a Bottom-up approach
void heapify(int arr[], int n, int i) {
// Find parent
int parent = (i - 1) / 2;
if (parent >= 0) {
// For Max-Heap
// If current node is greater than its parent
// Swap both of them and call heapify again
// for the parent
if (arr[i] > arr[parent]) {
swap(arr[i], arr[parent]);
// Recursively heapify the parent node
heapify(arr, n, parent);
}
}
}
// Function to insert a new node to the Heap
void insertNode(int arr[], int& n, int Key)
{
// Increase the size of Heap by 1
n = n + 1;
// Insert the element at end of Heap
arr[n - 1] = Key;
// Heapify the new node following a
// Bottom-up approach
heapify(arr, n, n - 1);
}
// A utility function to print array of size n
void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver Code
int main()
{
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
int arr[MAX] = { 10, 5, 3, 2, 4 };
int n = 5;
int key = 15;
insertNode(arr, n, key);
printArray(arr, n);
// Final Heap will be:
// 15
// / \
// 5 10
// / \ /
// 2 4 3
return 0;
}
Java
// Java program for implementing insertion in Heaps
public class insertionHeap {
// Function to heapify ith node in a Heap
// of size n following a Bottom-up approach
static void heapify(int[] arr, int n, int i)
{
// Find parent
int parent = (i - 1) / 2;
if (parent >= 0) {
// For Max-Heap
// If current node is greater than its parent
// Swap both of them and call heapify again
// for the parent
if (arr[i] > arr[parent]) {
// swap arr[i] and arr[parent]
int temp = arr[i];
arr[i] = arr[parent];
arr[parent] = temp;
// Recursively heapify the parent node
heapify(arr, n, parent);
}
}
}
// Function to insert a new node to the heap.
static int insertNode(int[] arr, int n, int Key)
{
// Increase the size of Heap by 1
n = n + 1;
// Insert the element at end of Heap
arr[n - 1] = Key;
// Heapify the new node following a
// Bottom-up approach
heapify(arr, n, n - 1);
// return new size of Heap
return n;
}
/* A utility function to print array of size n */
static void printArray(int[] arr, int n)
{
for (int i = 0; i < n; ++i)
System.out.println(arr[i] + " ");
System.out.println();
}
// Driver Code
public static void main(String args[])
{
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
// maximum size of the array
int MAX = 1000;
int[] arr = new int[MAX];
// initializing some values
arr[0] = 10;
arr[1] = 5;
arr[2] = 3;
arr[3] = 2;
arr[4] = 4;
// Current size of the array
int n = 5;
// the element to be inserted
int Key = 15;
// The function inserts the new element to the heap and
// returns the new size of the array
n = insertNode(arr, n, Key);
printArray(arr, n);
// Final Heap will be:
// 15
// / \
// 5 10
// / \ /
// 2 4 3
}
}
// The code is contributed by Gautam goel
Python3
# program to insert new element to Heap
# Function to heapify ith node in a Heap
# of size n following a Bottom-up approach
def heapify(arr, n, i):
parent = int(((i-1)/2))
# For Max-Heap
# If current node is greater than its parent
# Swap both of them and call heapify again
# for the parent
if parent >= 0:
if arr[i] > arr[parent]:
arr[i], arr[parent] = arr[parent], arr[i]
# Recursively heapify the parent node
heapify(arr, n, parent)
# Function to insert a new node to the Heap
def insertNode(arr, key):
global n
# Increase the size of Heap by 1
n += 1
# Insert the element at end of Heap
arr.append(key)
# Heapify the new node following a
# Bottom-up approach
heapify(arr, n, n-1)
# A utility function to print array of size n
def printArr(arr, n):
for i in range(n):
print(arr[i], end=" ")
# Driver Code
# Array representation of Max-Heap
'''
10
/ \
5 3
/ \
2 4
'''
arr = [10, 5, 3, 2, 4, 1, 7]
n = 7
key = 15
insertNode(arr, key)
printArr(arr, n)
# Final Heap will be:
'''
15
/ \
5 10
/ \ /
2 4 3
Code is written by Rajat Kumar....
'''
C#
// C# program for implementing insertion in Heaps
using System;
public class insertionHeap {
// Function to heapify ith node in a Heap of size n following a Bottom-up approach
static void heapify(int[] arr, int n, int i) {
// Find parent
int parent = (i - 1) / 2;
if (parent >= 0) {
// For Max-Heap
// If current node is greater than its parent
// Swap both of them and call heapify again
// for the parent
if (arr[i] > arr[parent]) {
// swap arr[i] and arr[parent]
int temp = arr[i];
arr[i] = arr[parent];
arr[parent] = temp;
// Recursively heapify the parent node
heapify(arr, n, parent);
}
}
}
// Function to insert a new node to the heap.
static int insertNode(int[] arr, int n, int Key) {
// Increase the size of Heap by 1
n = n + 1;
// Insert the element at end of Heap
arr[n - 1] = Key;
// Heapify the new node following a
// Bottom-up approach
heapify(arr, n, n - 1);
// return new size of Heap
return n;
}
/* A utility function to print array of size n */
static void printArray(int[] arr, int n) {
for (int i = 0; i < n; ++i)
Console.WriteLine(arr[i] + " ");
Console.WriteLine("");
}
public static void Main(string[] args) {
// Array representation of Max-Heap
// 10
// / \
// 5 3
// / \
// 2 4
// maximum size of the array
int MAX = 1000;
int[] arr = new int[MAX];
// initializing some values
arr[0] = 10;
arr[1] = 5;
arr[2] = 3;
arr[3] = 2;
arr[4] = 4;
// Current size of the array
int n = 5;
// the element to be inserted
int Key = 15;
// The function inserts the new element to the heap and
// returns the new size of the array
n = insertNode(arr, n, Key);
printArray(arr, n);
// Final Heap will be:
// 15
// / \
// 5 10
// / \ /
// 2 4 3
}
}
// This code is contributed by ajaymakvana.
JavaScript
// Javascript program for implement insertion in Heaps
// To heapify a subtree rooted with node i which is
// an index in arr[].Nn is size of heap
let MAX = 1000;
// Function to heapify ith node in a Heap of size n following a Bottom-up approach
function heapify(arr, n, i)
{
// Find parent
let parent = Math.floor((i-1)/2);
if (parent >= 0) {
// For Max-Heap
// If current node is greater than its parent
// Swap both of them and call heapify again
// for the parent
if (arr[i] > arr[parent]) {
let temp = arr[i];
arr[i] = arr[parent];
arr[parent] = temp;
// Recursively heapify the parent node
heapify(arr, n, parent);
}
}
}
// Function to insert a new node to the Heap
function insertNode(arr, n, Key)
{
// Increase the size of Heap by 1
n = n + 1;
// Insert the element at end of Heap
arr[n - 1] = Key;
// Heapify the new node following a
// Bottom-up approach
heapify(arr, n, n - 1);
return n;
}
/* A utility function to print array of size N */
function printArray(arr, n)
{
for (let i = 0; i < n; ++i)
console.log(arr[i] + " ");
console.log("</br>");
}
let arr = [ 10, 5, 3, 2, 4 ];
let n = arr.length;
let key = 15;
n = insertNode(arr, n, key);
printArray(arr, n);
// This code is contributed by ajaymakvana
Time Complexity: O(log(n)) (where n is no of elements in the heap)
Auxiliary Space: O(n)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read