Heap Sort Program in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Heap Sort in C - Sorting Algorithm

šŸ“‘ On this page:
  • Introduction
  • C Program for Heap Sort
  • Sample Output
  • Program Explanation
  • Step-by-Step Approach
  • Time & Space Complexity
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What is Heap Sort algorithm and how it works
  • How to implement Heap Sort in C programming
  • What is a Max Heap and how to build it
  • How to use the heapify function
  • Time and space complexity analysis

Introduction to Heap Sort

Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It works by first building a max heap from the input array, then repeatedly extracting the largest element from the heap and placing it at the end of the array.

A binary heap is a complete binary tree where each node is greater than or equal to its children (max heap) or less than or equal to its children (min heap). Heap Sort uses a max heap to sort in ascending order.

Key characteristics of Heap Sort:

  • In-place algorithm: Sorts the array without using extra memory
  • Not stable: Does not preserve the relative order of equal elements
  • Guaranteed O(n log n) performance: Works consistently well
  • Useful for priority queues: Efficient for finding largest/smallest elements

šŸ’” How it works: Heap Sort builds a max heap from the array, then repeatedly swaps the root (largest element) with the last element, reduces the heap size, and heapifies the new root.

C Program for Heap Sort

#include <stdio.h>

// Function to swap two elements
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Function to heapify a subtree rooted at index i
// n is the size of the heap
void heapify(int arr[], int n, int i) {
    int largest = i;       // Initialize largest as root
    int left = 2 * i + 1;  // Left child index
    int right = 2 * i + 2; // Right child index

    // If left child is larger than root
    if (left < n && arr[left] > arr[largest]) {
        largest = left;
    }

    // If right child is larger than largest so far
    if (right < n && arr[right] > arr[largest]) {
        largest = right;
    }

    // If largest is not root, swap and continue heapifying
    if (largest != i) {
        swap(&arr[i], &arr[largest]);
        // Recursively heapify the affected subtree
        heapify(arr, n, largest);
    }
}

// Main function to perform heap sort
void heapSort(int arr[], int n) {
    // Build max heap (rearrange array)
    // Start from the last non-leaf node
    for (int i = n / 2 - 1; i >= 0; i--) {
        heapify(arr, n, i);
    }

    // One by one extract elements from heap
    for (int i = n - 1; i > 0; i--) {
        // Move current root to end
        swap(&arr[0], &arr[i]);

        // Call max heapify on the reduced heap
        heapify(arr, i, 0);
    }
}

// Function to print the array
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Driver program to test the heap sort
int main() {
    int arr[] = {12, 11, 13, 5, 6, 7, 1, 9, 3, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    heapSort(arr, n);

    printf("Sorted array:   ");
    printArray(arr, n);

    return 0;
}

Sample Output

Original array: 12 11 13 5 6 7 1 9 3 10
Sorted array:   1 3 5 6 7 9 10 11 12 13

Another Example:

Original array: 45 23 78 12 56 34 89 10 67 90
Sorted array:   10 12 23 34 45 56 67 78 89 90

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Swap Function: swap() exchanges two integer values using a temporary variable.
  3. Heapify Function:
    • Takes an array, heap size n, and index i
    • Finds the largest among root, left child, and right child
    • If root is not largest, swaps and recursively heapifies the affected subtree
    • This maintains the max heap property
  4. HeapSort Function:
    • Step 1 - Build Max Heap: Starting from the last non-leaf node (n/2 - 1) up to root, call heapify
    • Step 2 - Extract Elements: Swap root (largest) with last element, reduce heap size, heapify the new root
    • Repeat until all elements are sorted
  5. PrintArray Function: Displays all elements of the array.
  6. Main Function:
    • Creates an unsorted array
    • Displays the original array
    • Calls heapSort() to sort
    • Displays the sorted array

šŸ“ Note: The heapify function is called recursively. Each call has O(log n) time complexity, and it's called O(n) times, giving us the overall O(n log n) performance.

Step-by-Step Approach

Step Action Explanation
1Build Max HeapConvert array into a max heap structure
2Extract RootSwap root with last element
3HeapifyRestore heap property for reduced heap
4RepeatContinue until all elements are sorted

Algorithm for Heap Sort

  1. Build Max Heap:
    • For i = n/2 - 1 down to 0:
      • Call heapify(arr, n, i)
  2. Sort:
    • For i = n - 1 down to 1:
      • Swap arr[0] and arr[i]
      • Call heapify(arr, i, 0)
  3. Done: Array is now sorted in ascending order

Time & Space Complexity

Complexity Best Case Average Case Worst Case
Time O(n log n) O(n log n) O(n log n)
Space O(1) - In-place sorting

šŸ“Š Key Points:

  • Heap Sort has guaranteed O(n log n) time complexity in all cases
  • It is an in-place algorithm (O(1) extra space)
  • Not stable - equal elements may not retain their original order
  • Faster than merge sort for large datasets due to in-place nature

šŸ’» Practice Exercise

Challenge 1: Modify the program to sort the array in descending order using Heap Sort.

Challenge 2: Write a program to find the kth largest element in an array using Heap Sort.

Challenge 3: Implement Heap Sort on an array of strings (lexicographical order).

šŸ” Click to Show Solution for Challenge 1
// To sort in descending order, use MIN HEAP instead of MAX HEAP
// Change the comparison in heapify function:

if (left < n && arr[left] < arr[smallest]) {
    smallest = left;
}

if (right < n && arr[right] < arr[smallest]) {
    smallest = right;
}

// This creates a min heap, resulting in descending order
// after extraction.
šŸ” Click to Show Solution for Challenge 2
int findKthLargest(int arr[], int n, int k) {
    // Build max heap
    for (int i = n/2 - 1; i >= 0; i--)
        heapify(arr, n, i);
    
    // Extract k-1 elements
    for (int i = n-1; i > n-k; i--) {
        swap(&arr[0], &arr[i]);
        heapify(arr, i, 0);
    }
    return arr[0]; // kth largest
}

Frequently Asked Questions

1. What is the difference between Heap Sort and other sorting algorithms?

Heap Sort has guaranteed O(n log n) performance, while Quick Sort has O(n log n) average but O(n²) worst case. Merge Sort has O(n log n) but requires O(n) extra space. Heap Sort is in-place, making it memory efficient.

2. Why do we build a max heap for ascending order?

A max heap ensures the largest element is at the root. By repeatedly removing the root (largest element) and placing it at the end, we build the sorted array from largest to smallest, resulting in ascending order.

3. Is Heap Sort stable?

No, Heap Sort is not stable. Equal elements may not retain their original relative order because the sorting process doesn't consider the original positions of equal elements.

4. When should I use Heap Sort?

Heap Sort is ideal when:

  • You need guaranteed O(n log n) performance
  • Memory usage is a concern (in-place sorting)
  • You're implementing priority queues
  • You need to find kth largest/smallest elements

5. What is the space complexity of Heap Sort?

Heap Sort has O(1) space complexity (in-place) because it only uses a constant amount of extra memory for variables like loop counters and temporary storage during swaps.

šŸ’” Tip: Heap Sort is an excellent choice when you need consistent performance regardless of input data distribution.

šŸ“– Related Tutorials

  • Quick Sort in C
  • Merge Sort in C
  • Bubble Sort in C
  • Binary Search in C

Previous Topic: -->> Quick Sort in C   ||   Next topic: -->> Merge Sort in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.