Ads Cia-3
Ads Cia-3
CIA-03 Activity of
Heap Sorting
CONTENT
Introduction of Heap
Min heap
Max heap
Working of heap
Example
Difference
Advantages
Disadvantages
Conclusion
Reference
Introduction of Heap
Heap sort is an efficient comparison-based sorting algorithm that:
Creates a heap from the input array.
Then sorts the array by taking advantage of a heap's properties.
The concept of heap sort is to eliminate the element one by one from the heap part of
the list And then insert them into the sorted part of the list
Heap sort is similar to the selection sort where we first find the minimum element and
place minimum element at beginning. Repeat the same process for remaining element.
Heap sort is an in-place algorithm
The time complexity of heap sort is O(nlogn).
A Heap is a special Tree-based data structure in which the tree is a complete binary tree.
Since a heap is a complete binary tree, a heap with N nodes has log N height.
It is useful to remove the highest or lowest priority element.
There are two types of Heaps in the data structure.
1) MIN HEAP 2) MAX HEAP
In a Min-Heap
the
key
present
at
the
root
node
In a Max-Heap the key present at the root node
must be less than or equal among the keys must be greater than or equal among the keys
present at all of its children. present at all of its children.
The same property must be recursively true for The same property must be recursively true for
all sub-trees in that Binary Tree. all sub-trees in that Binary Tree.
In a Min-Heap the minimum key element present In a Max-Heap the maximum key element
at the root. present at the root.
Below is the Binary Tree that satisfies all the Below is the Binary Tree that satisfies all the
property of Min Heap. property of Max Heap.
Heapify Method:
Heapify is the process of creating a heap data structure from a binary tree represented using an array. It
is used to create Min-Heap or Max-heap. Start from the last index of the non-leaf node whose index is
given by n/2 – 1. Heapify uses recursion.
How does Heapify work?
12
Array :- 12 11 13 5 6 7
11 13
5 6 7
MAX HEAP is created using heapify method.
13
11 12
5 6 7
8 4 7 1 3 5
8 8 7 8
7 8 5 7 8 5 7 8 4 5 7 8
4 5 7 8 3 4 5 7 8
Final Array
1 3 4 5 7 8
Difference
HEAP SORT BUBBLE SORT SELECTION SORT
Defination Heapsort is a popular The bubble sort repeatedly Selection sorting is a sorting
and efficient sorting algorithm. compares the adjacent elements algorithm where we select the
The concept of heap sort is to and swaps them if they are not in minimum element from the array
eliminate the elements one by one the correct order. and put that at its correct position.
from the heap part of the list, and
then insert them into the sorted
part of the list.
Approach It acts like the divide It is based on the subtract and Selection sort performs minimum
and conquer conquer number of swaps to sort the array.
technique. method.