#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Counting Sort in Data Structure

Counting Sort is a non-comparison-based sorting algorithm that counts the number of occurrences of each distinct value in the input, then uses those counts to place elements directly into their sorted position.

Algorithm Steps

  • Find the range of input values (minimum and maximum).
  • Create a count array to store the frequency of each value.
  • Transform the count array so each element holds the cumulative count (sum of previous counts).
  • Place each input element into the output array based on its cumulative count, then decrement the count.
def counting_sort(arr):
    if not arr:
        return arr
    max_val = max(arr)
    count = [0] * (max_val + 1)
    for num in arr:
        count[num] += 1
    for i in range(1, len(count)):
        count[i] += count[i - 1]

    output = [0] * len(arr)
    for num in reversed(arr):
        count[num] -= 1
        output[count[num]] = num
    return output

Complexity

MetricValue
TimeO(n + k)
SpaceO(n + k)

Here n is the number of elements and k is the range of input values. Counting Sort is efficient only when k is not significantly larger than n.

Applications

  • Sorting grades, ages, or other bounded-range integer data.
  • Used as a subroutine within Radix Sort.
  • Frequency-based data analysis.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course