Heap Sort
Small joke for you guys 😜😜😜😜😜
Why did the array apply for therapy? It had too many issues with heapsort-emotional baggage! 😂
What is heap sort
Heap sort is an efficient sorting algorithm, which is based on the comparison of elements.
It works using the Binary Heap data structure, and in most of the cases we use the Max heap, but based on requirements , we can use the Min heap concept as well.
Wait Wait Wait ….. Could you please let me know what is Heeeeeaaaaapppppp… 🤯
Heap data structures are often implemented using arrays, where the parent-child relationships can be represented efficiently. The root of the heap (index 0 in the array) represents the maximum or minimum element, depending on whether it’s a max-heap or min-heap.
Max-Heap:
In a max-heap, for every node ‘i’ other than the root, the value of ‘i’ is less than or equal to the value of its parent. This means that the largest element in the heap is at the root.
if A is an array representing the max heap, and i is an index such that
1≤ i ≤ A.length, then A[parent(i)] ≥ A[i]
Min-Heap:
In a min-heap, for every node ‘i’ other than the root, the value of ‘i’ is greater than or equal to the value of its parent. This means that the smallest element in the heap is at the root.
if A is an array representing the max heap, and i is an index such that
1 ≤ i ≤ A.length, then A[parent(i)] ≤ A[i]
Okay how I can visualize, could you please help me with that.
🤣🤣🤣🤣🤣
Lets laugh first 😜😜😜😜😜
“Picture a heap like a tree where each element competes to be the ‘top banana’ or the ‘humblest potato,’ depending on the mood. Turning an array into a heap is like organizing a potluck — everyone needs to know their place.
Hope you gotcha! how to visualize heap… with my awesome drawing skills 🤣😂
Reasons why heap sort might a choice:
1) This is an in-place sorting algorithm, means ,
- No more additional space needed to sort elements, same array can be used
2) The worst-case time complexity of heap sort is O(n log n), which is the same as quicksort and mergesort, means,
Heap sort efficient for large datasets, especially when worst-case performance is a concern.
3) It has a predictable behavior means,
The same input should always produce the same sorted output.
Despite its advantages, heap sort is not always the best choice
1) Heap sort is not a stable sorting algorithm. However, in certain applications, stability is not a critical requirement, and the efficiency of heap sort may outweigh the need for stability.
2) It may be outperformed by other algorithms like quicksort or mergesort in certain scenarios, depending on factors such as the size of the dataset, available memory, and the distribution of the data.
Heap Sort Algorithm
Funny way to explain LOL 🤣🤣🤣🤣🤣
Heap sort is basically the sorting version of musical chairs, where elements find their spot one by one until the music stops and voilà, you’ve got a sorted array.
Lets see the
- English Algo
- Code in Swift
- Code in Java
Heap sort just have 3 simple steps Guys… yeahhhhhh…..we all can remember…
# Step 1: Build Max Heap -> Starting from last node
# Step 2: Extract Max, Swap and ….. Lol 🤣 Just repeat the algo again.
Both Step1 and Step2 will use a common function known as Heapify
Heapify ->
Get Unleased_Coder’s stories in your inbox
Join Medium for free to get updates from this writer.
Will max sure that for every index i, we would definitely re-arrange the array in a way that it must be the Max Heap and it satisfies that rule
means at any i is an index such that 1 ≤ i ≤ A.length, then A[parent(i)] ≤ A[i]
For detailed explanation
1) Build Max Heap:
Start from the last non-leaf node ([n/2] −1) and move upward to the root.
For each node i, perform the Heapify operation to ensure the max heap property:
If the left child (2n+1) exists and is greater than the node at i, swap them.
If the right child (2n+2) exists and is greater than the node at i (or the left child), swap them.
Recursively apply Heapify to the affected subtree.
Continue this process until the entire array satisfies the max heap property.
Build_Max_Heap(arr):
n = arr.length;
for (i = n / 2 - 1; i >= 0; i--) {
Heapify(arr, n, i)
}3) Extract Max, Swap, and Repeat:
After building the max heap, the largest element is at the root. Swap it with the last element of the array and reduce the size of the heap (n−1).
Perform Heapify on the root to maintain the max heap property.
Repeat this process until the entire array is sorted.
Heap_Sort(arr):
Build_Max_Heap(arr)
// Step 3
for i from n-1 to 1:
swap(arr[0], arr[i])
Heapify(arr, i, 0)Heapify: the common function.
Given an array and an index i:
Compare the element at i with its left child (2i+1) and right child (2i+2).
If the left or right child is greater, swap the element at i with the greater child.
Recursively apply Heapify to the affected subtree.
Base case: Stop when the subtree rooted at i satisfies the max heap property.
Heapify(arr, n, i):
largest = i
left_child = 2 * i + 1
right_child = 2 * i + 2
if left_child < n and arr[left_child] > arr[largest]:
largest = left_child
if right_child < n and arr[right_child] > arr[largest]:
largest = right_child
if largest != i:
swap(arr[i], arr[largest])
Heapify(arr, n, largest)If you want to see the detailed explanations, watch my youtube unorganised video 🤣🤣🤣🤣🤣
Git Repo : https://github.com/MamtaiOS13/HeapSort/tree/main
Need Code Please :
In Swift
import UIKit
func heapify(a: inout [Int], n: Int, index: Int) {
var large = index
var lc = 2*index + 1
var rc = 2*index + 2
// check if left child value is large
if (lc < n && a[lc] > a[large]) {
large = lc
}
// check if right child value is large
if (rc < n && a[rc] > a[large]) {
large = rc
}
// base case to break the recursion
if (large != index) {
let temp = a[index]
a[index] = a[large]
a[large] = temp
heapify(a: &a, n: n, index: large)
}
}
func buildMaxHeap(a: inout [Int]) {
let n = a.count
for i in (0...(n / 2 - 1)).reversed() {
// Step1 and Step2 both uses heapify
heapify(a: &a, n: n, index: i)
}
}
func heapSort(a: inout [Int]) {
let n = a.count
// Step 1
buildMaxHeap(a: &a)
// Step 2
for i in (1..<n).reversed() {
// Swap elements
let temp = a[0]
a[0] = a[i]
a[i] = temp
// Step1 and Step2 both uses heapify
heapify(a: &a, n: i, index: 0)
}
}
var a = [12, 11, 13, 5, 6, 7]
print("Old Array :", a)
heapSort(a: &a)
print("\nNew Sorted Array :", a)In Java
public class HeapSort {
public static void heapify(int[] a, int n, int i) {
int large = i ;
int lc = 2*i + 1;
int rc = 2*i + 2;
// check if left child value is large
if (lc < n && a[lc] > a[large]) {
large = lc;
}
// check if right child value is large
if (rc < n && a[rc] > a[large]) {
large = rc;
}
// base case to break the recursion
if(large != i) {
swap(a, i, large);
heapify(a, n, large);
}
}
public static void buildMaxHeap(int[] a) {
int n = a.length;
for(int i = n/2 - 1; i >= 0; i--){
//Step1 and Step2 both uses heapify
heapify(a, n, i);
}
}
public static void swap(int[] a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void printArray(int[] a){
for(int num : a) {
System.out.print(num + " ");
}
}
public static void heapSort(int[] a) {
int n = a.length;
// Step 1
buildMaxHeap(a);
// Step 2
for(int i = n-1 ; i > 0; i--){
swap(a, 0, i);
//Step1 and Step2 both uses heapify
heapify(a, i, 0);
}
}
public static void main(String[] args) {
int[] a = {12, 11, 13, 5, 6, 7};
System.out.println("Old Array");
printArray(a);
heapSort(a);
System.out.println();
System.out.println("New Array");
printArray(a);
System.out.println();
}
}Lets learn about few factors before you choose any sorting alogs.
- Time Complexity:
This is one of the most crucial factors. The time complexity of a sorting algorithm indicates how the algorithm’s performance scales with the size of the input data. Common notations for time complexity include O(n²), O(n log n), and O(n).
2. Space Complexity:
Some sorting algorithms require additional memory space to perform their operations, while others can sort the data in-place, without requiring extra memory. In-place algorithms are often preferred in situations where memory usage is a concern.
3. Stability:
A sorting algorithm is stable if the relative order of equal elements remains unchanged after sorting. Stability is important in situations where you want to preserve the original order of equal elements.
What is this even means? 🫣
Let say [1,1,3] ….here both 1, 1 should be in the same order after sorting the array is what we need defines the Stability in nature.
4. Adaptability:
An adaptive sorting algorithm performs better when the input data is partially ordered. If a large portion of the input data is already sorted, an adaptive algorithm can take advantage of this and improve its performance.
What is this even means? 🫣
Means if we have partially sorted array then the performance of sorting algos should be optimised
5. Ease of Implementation:
Some sorting algorithms are simpler to implement than others. The ease of implementation can be a significant factor, especially for smaller datasets or situations where simplicity and clarity are prioritized over optimal performance.
6. Average and Worst-Case Scenarios:
Understanding the average and worst-case time complexities is essential. In some cases, an algorithm might perform well on average but have a poor worst-case scenario, which could be critical in certain applications.
-> Will create one more post on the time and space complexity….
7. Data Distribution:
The distribution of data (uniform, partially ordered, reverse ordered, etc.) can influence the performance of different sorting algorithms. Some algorithms may perform better on certain types of data distributions.
8. Best-Case Scenario:
While worst-case performance is often the focus, considering the best-case scenario is also important. For some algorithms, the best-case scenario might be a significant factor in choosing the right algorithm.
9. Size of Data:
The size of the dataset can influence the choice of sorting algorithm. Some algorithms perform better on small datasets, while others are designed for efficient sorting of large datasets.
10. Hardware Constraints:
The characteristics of the hardware on which the algorithm will run can also be a consideration. Some algorithms may be better suited for parallel processing or take advantage of specific hardware features.
11. External Sorting:
For sorting large datasets that do not fit into memory, external sorting algorithms that efficiently use external storage (such as disk drives) become relevant.
12. Programming Language and Libraries:
The programming language and available libraries can influence the choice of sorting algorithm. Some languages provide built-in sorting functions that are optimized for performance.
Yup, we are done.
To inspire me, to write more articles like this, kindly follow me
Kindly feel free to leave a comment or question. I will be really happy in receiving your feedback.
Have You Found It Useful? Comment IT









