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

Counting Sort in C - Linear Sorting Algorithm

📑 On this page:
  • Introduction
  • C Program for Counting 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 Counting Sort and when to use it
  • How to implement Counting Sort in C programming
  • How to handle negative numbers and large ranges
  • Time and space complexity analysis
  • When Counting Sort is better than comparison-based sorts

Introduction to Counting Sort

Counting Sort is a non-comparison-based sorting algorithm that sorts integers by counting the occurrences of each unique element. Unlike comparison-based algorithms (like Quick Sort or Merge Sort), Counting Sort uses the actual values of the elements as indices into an array.

Key characteristics of Counting Sort:

  • Linear time complexity: O(n + k) where k is the range of input
  • Stable: Preserves the relative order of equal elements
  • Not in-place: Requires extra memory for counting and output arrays
  • Efficient for small integer ranges: Works best when the range of values is not too large

💡 When to use: Counting Sort is ideal when you know the range of values is small (e.g., test scores from 0-100, ages, or grades). It's perfect for sorting integers with a limited range.

C Program for Counting Sort

#include <stdio.h>
#include <stdlib.h>

// Function to find the maximum element in an array
int findMax(int arr[], int n) {
    int max = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

// Function to find the minimum element in an array
int findMin(int arr[], int n) {
    int min = arr[0];
    for (int i = 1; i < n; i++) {
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return min;
}

// Counting Sort function
void countingSort(int arr[], int n) {
    // Find the range of values
    int min = findMin(arr, n);
    int max = findMax(arr, n);
    int range = max - min + 1;

    // Create count array and output array
    int *count = (int *)calloc(range, sizeof(int));
    int *output = (int *)malloc(n * sizeof(int));

    // Count occurrences of each element
    for (int i = 0; i < n; i++) {
        count[arr[i] - min]++;
    }

    // Modify count array to store cumulative counts
    for (int i = 1; i < range; i++) {
        count[i] += count[i - 1];
    }

    // Build the output array
    for (int i = n - 1; i >= 0; i--) {
        int index = arr[i] - min;
        output[count[index] - 1] = arr[i];
        count[index]--;
    }

    // Copy output array back to original array
    for (int i = 0; i < n; i++) {
        arr[i] = output[i];
    }

    // Free allocated memory
    free(count);
    free(output);
}

// 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 counting sort
int main() {
    int arr[] = {4, 2, 2, 8, 3, 3, 1, 5, 7, 6, 9, 2, 4, 6, 8};
    int n = sizeof(arr) / sizeof(arr[0]);

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

    countingSort(arr, n);

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

    return 0;
}

Sample Output

Original array: 4 2 2 8 3 3 1 5 7 6 9 2 4 6 8
Sorted array:   1 2 2 2 3 3 4 4 5 6 6 7 8 8 9

Example with negative numbers:

Original array: -5 -2 8 0 3 -1 4 7 -3 6
Sorted array:   -5 -3 -2 -1 0 3 4 6 7 8

Program Explanation

Let's break down the code step by step:

  1. Include Header Files: #include <stdio.h> and #include <stdlib.h> for input/output and memory allocation.
  2. Find Min and Max:
    • findMax() and findMin() determine the range of values
    • This allows the algorithm to handle negative numbers and any integer range
  3. Counting Sort Function:
    • Step 1: Find range = max - min + 1
    • Step 2: Create a count array of size 'range' initialized to 0
    • Step 3: Count occurrences: count[arr[i] - min]++
    • Step 4: Cumulative count: count[i] += count[i-1]
    • Step 5: Build output array by placing elements in sorted order
    • Step 6: Copy output back to original array
  4. Memory Management: Uses calloc() and malloc() for dynamic memory allocation, and free() to prevent memory leaks.
  5. PrintArray Function: Displays all elements of the array.
  6. Main Function:
    • Creates an unsorted array
    • Displays the original array
    • Calls countingSort() to sort
    • Displays the sorted array

📝 Note: Counting Sort is stable, meaning equal elements maintain their relative order. This is important when sorting data with multiple keys.

Step-by-Step Approach

Step Action Explanation
1Find RangeDetermine min and max values
2Create Count ArrayAllocate array of size 'range'
3Count OccurrencesCount frequency of each element
4Cumulative CountCalculate positions in sorted array
5Build OutputPlace elements in sorted order
6Copy BackCopy sorted elements to original array

Algorithm for Counting Sort

  1. Find Range:
    • min = findMin(arr, n)
    • max = findMax(arr, n)
    • range = max - min + 1
  2. Count Occurrences:
    • For each element arr[i], increment count[arr[i] - min]
  3. Cumulative Count:
    • For i = 1 to range-1: count[i] += count[i-1]
  4. Build Output:
    • For i = n-1 down to 0:
    • index = arr[i] - min
    • output[count[index] - 1] = arr[i]
    • count[index]--
  5. Copy Back: Copy output array to original array

Time & Space Complexity

Complexity Best Case Average Case Worst Case
Time O(n + k) O(n + k) O(n + k)
Space O(k) - Extra space for count array

📊 Key Points:

  • Linear time: Counting Sort runs in O(n + k) time, where k is the range of input
  • Space trade-off: Extra memory O(k) is needed for the count array
  • Stable: Preserves relative order of equal elements
  • Best for: Small integer ranges with high performance requirements

💻 Practice Exercise

Challenge 1: Modify the program to sort an array of characters (e.g., 'a', 'b', 'c') using Counting Sort.

Challenge 2: Write a program to sort an array of student grades (0-100) using Counting Sort.

Challenge 3: Implement Counting Sort for an array where the range is very large (e.g., 0 to 1,000,000) and optimize it.

🔍 Click to Show Solution for Challenge 1
// For characters, convert to ASCII values
void countingSortChar(char arr[], int n) {
    // ASCII range: 0-255
    int range = 256;
    int *count = (int *)calloc(range, sizeof(int));
    char *output = (char *)malloc(n * sizeof(char));
    
    for (int i = 0; i < n; i++) {
        count[(int)arr[i]]++;
    }
    
    for (int i = 1; i < range; i++) {
        count[i] += count[i-1];
    }
    
    for (int i = n-1; i >= 0; i--) {
        int idx = (int)arr[i];
        output[count[idx] - 1] = arr[i];
        count[idx]--;
    }
    
    for (int i = 0; i < n; i++) {
        arr[i] = output[i];
    }
    
    free(count);
    free(output);
}
🔍 Click to Show Solution for Challenge 2
// Grade sorting (0-100 range)
void sortGrades(int grades[], int n) {
    // Range: 0 to 100
    const int MAX_GRADE = 100;
    int count[MAX_GRADE + 1] = {0};
    int output[n];
    
    for (int i = 0; i < n; i++) {
        count[grades[i]]++;
    }
    
    for (int i = 1; i <= MAX_GRADE; i++) {
        count[i] += count[i-1];
    }
    
    for (int i = n-1; i >= 0; i--) {
        output[count[grades[i]] - 1] = grades[i];
        count[grades[i]]--;
    }
    
    for (int i = 0; i < n; i++) {
        grades[i] = output[i];
    }
}

Frequently Asked Questions

1. When should I use Counting Sort?

Counting Sort is best when the range of possible values (k) is not significantly larger than the number of elements (n). It's ideal for sorting integers with a small, known range like exam scores, ages, or ASCII characters.

2. Why is Counting Sort not suitable for large ranges?

Counting Sort requires O(k) extra space for the count array. If the range is huge (e.g., 0 to 1,000,000,000), the memory usage becomes impractical, making other algorithms more suitable.

3. Is Counting Sort faster than Quick Sort?

For small integer ranges, yes! Counting Sort runs in O(n + k) time, which is linear. Quick Sort has O(n log n) average complexity. However, for large ranges, Quick Sort may be more practical due to space constraints.

4. Can Counting Sort handle negative numbers?

Yes! By finding the minimum value and using it as an offset, we can map negative numbers to positive indices in the count array. The code above implements this using the arr[i] - min technique.

5. Is Counting Sort stable?

Yes, Counting Sort is stable. It preserves the relative order of equal elements because we iterate from the end of the array when building the output, which maintains the original order of duplicate elements.

💡 Pro Tip: Counting Sort is an excellent choice for sorting data with a limited range, such as sorting test scores, student grades, or counting frequencies in data analysis.

📖 Related Tutorials

  • Heap Sort in C
  • Quick Sort in C
  • Merge Sort in C
  • Radix Sort in C

Previous Topic: -->> Heap Sort in C   ||   Next topic: -->> Radix 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.