Implementing counting sort in JavaScript

In the given task, our aim is to create a counting sorting technique and implement this problem with the help of Javascript functionalities.

What is Counting Sort?

Counting sort is a non-comparison based sorting algorithm that works by counting the occurrences of each distinct element in the input array. It determines the position of each element in the sorted output by calculating how many elements are smaller than it.

The algorithm works in several phases:

  • Find the minimum and maximum values in the input array
  • Create a count array to store frequency of each element
  • Calculate prefix sums to determine positions
  • Place elements in their correct sorted positions
Input Array: [4, 2, 2, 8, 3, 3, 1] Step 1: Count frequencies 1 1 2 2 3 2 4 1 8 1 Step 2: Calculate prefix sums 1 1 2 3 3 5 4 6 8 7 Step 3: Sorted Output 1 2 2 3 3 4 8 Value Count

Algorithm Steps

Step 1 ? Check if the array has elements, return if empty

Step 2 ? Find minimum and maximum values to determine the range

Step 3 ? Create count array and initialize with zeros

Step 4 ? Count occurrences of each element

Step 5 ? Calculate prefix sums for position mapping

Step 6 ? Place elements in output array using count positions

Implementation

function countingSort(arr) {
   if (arr.length === 0) {
      return arr;
   }
    
   // Find the range of values in the input array
   let min = arr[0];
   let max = arr[0];
   for (let i = 1; i < arr.length; i++) {
      if (arr[i] < min) {
         min = arr[i];
      }
      if (arr[i] > max) {
         max = arr[i];
      }
   }
    
   // Initialize count array and output array
   const count = new Array(max - min + 1).fill(0);
   const output = new Array(arr.length);
    
   // Count occurrences of each element
   for (let i = 0; i < arr.length; i++) {
      count[arr[i] - min]++;
   }
    
   // Calculate prefix sum for position mapping
   for (let i = 1; i < count.length; i++) {
      count[i] += count[i - 1];
   }
    
   // Build output array in reverse order for stability
   for (let i = arr.length - 1; i >= 0; i--) {
      output[count[arr[i] - min] - 1] = arr[i];
      count[arr[i] - min]--;
   }
   
   return output;
}

// Example usage
const arr = [30, 10, 40, 10, 50, 90, 20, 60, 50, 30, 50];
console.log("Original array:", arr);
console.log("Sorted array:", countingSort(arr));
Original array: [30, 10, 40, 10, 50, 90, 20, 60, 50, 30, 50]
Sorted array: [10, 10, 20, 30, 30, 40, 50, 50, 50, 60, 90]

Example with Small Array

// Demonstrating step by step with smaller array
function countingSortDetailed(arr) {
   console.log("Input array:", arr);
   
   if (arr.length === 0) return arr;
   
   // Find min and max
   let min = Math.min(...arr);
   let max = Math.max(...arr);
   console.log("Min:", min, "Max:", max);
   
   // Create count array
   const count = new Array(max - min + 1).fill(0);
   
   // Count occurrences
   for (let i = 0; i < arr.length; i++) {
      count[arr[i] - min]++;
   }
   console.log("Count array:", count);
   
   // Calculate prefix sums
   for (let i = 1; i < count.length; i++) {
      count[i] += count[i - 1];
   }
   console.log("Prefix sums:", count);
   
   // Build output
   const output = new Array(arr.length);
   for (let i = arr.length - 1; i >= 0; i--) {
      output[count[arr[i] - min] - 1] = arr[i];
      count[arr[i] - min]--;
   }
   
   return output;
}

const smallArr = [4, 2, 2, 8, 3, 3, 1];
console.log("Sorted:", countingSortDetailed(smallArr));
Input array: [4, 2, 2, 8, 3, 3, 1]
Min: 1 Max: 8
Count array: [1, 2, 2, 1, 0, 0, 0, 1]
Prefix sums: [1, 3, 5, 6, 6, 6, 6, 7]
Sorted: [1, 2, 2, 3, 3, 4, 8]

Time and Space Complexity

Complexity Best Case Average Case Worst Case
Time O(n + k) O(n + k) O(n + k)
Space O(k) O(k) O(k)

Where n is the number of elements and k is the range of input values (max - min + 1).

When to Use Counting Sort

Counting sort is most effective when:

  • The range of input values is small relative to the number of elements
  • Working with non-negative integers or easily mappable values
  • Stability is required (equal elements maintain relative order)
  • Linear time complexity is needed

Conclusion

Counting sort provides O(n + k) time complexity, making it faster than comparison-based algorithms when the range is small. It's particularly useful for sorting integers within a known range and maintains stability of equal elements.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements