Counting Sort is a simple yet powerful sorting algorithm that works well when you know the range of input numbers in advance. Unlike comparison-based algorithms like Quick Sort or Merge Sort, Counting Sort doesn’t compare elements directly. Instead, it counts how many times each number appears and then calculates the positions of each element in the sorted array. This makes it very fast and efficient for certain types of data, especially integers with a limited range.
with hands-on learning.
get the skills and confidence to land your next move.
Understanding Counting Sort is important for beginners because it introduces a different approach to sorting—one that focuses on counting rather than comparing. It is often used in situations where speed is crucial, such as sorting scores, ages, or small sets of integers. By learning Counting Sort in JavaScript, beginners gain insight into an algorithm that is easy to implement but highly effective in practice.
Program 1: Basic Counting Sort
This program demonstrates a simple Counting Sort implementation in JavaScript for arrays containing positive integers.
function countingSort(arr) {
let max = Math.max(...arr);
let count = Array(max + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
let sorted = [];
for (let i = 0; i < count.length; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let numbers = [4, 2, 2, 8, 3, 3, 1];
console.log("Sorted array:", countingSort(numbers));In this program, we first find the largest number to determine the size of the counting array. We then count how many times each number occurs and finally build the sorted array by repeating each number according to its count. Beginners can understand Counting Sort as simply keeping track of occurrences and arranging numbers based on those counts.
Program 2: Counting Sort with output array
This version uses an output array to store sorted elements, which is closer to the standard textbook implementation.
function countingSortOutput(arr) {
let max = Math.max(...arr);
let count = Array(max + 1).fill(0);
let output = Array(arr.length).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
for (let i = 1; i < count.length; i++) {
count[i] += count[i - 1];
}
for (let i = arr.length - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
return output;
}
let values = [4, 2, 2, 8, 3, 3, 1];
console.log("Sorted array:", countingSortOutput(values));Here, the output array ensures stability, meaning that equal numbers maintain their original relative positions. Beginners can see how Counting Sort can preserve order while efficiently arranging numbers. It is useful when the order of similar items matters, such as sorting objects with integer keys.
Program 3: Counting Sort handling zeros and repeated numbers
This example highlights how Counting Sort naturally handles zeros and repeated elements without extra work.
function countingSortZeros(arr) {
let max = Math.max(...arr);
let count = Array(max + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
let sorted = [];
for (let i = 0; i < count.length; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let numbersWithZeros = [0, 5, 3, 0, 2, 3, 1];
console.log("Sorted array:", countingSortZeros(numbersWithZeros));Counting Sort counts zeros just like any other number, making it convenient for datasets where zeros occur. Beginners will understand that Counting Sort doesn’t require special handling for repeated or zero values, which simplifies the logic.
Program 4: Counting Sort in descending order
This program demonstrates how to modify Counting Sort to sort numbers in descending order.
function countingSortDescending(arr) {
let max = Math.max(...arr);
let count = Array(max + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
let sorted = [];
for (let i = count.length - 1; i >= 0; i--) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let valuesDesc = [4, 2, 2, 8, 3, 3, 1];
console.log("Sorted array (descending):", countingSortDescending(valuesDesc));By simply iterating the count array backward, we can sort in descending order. Beginners can see that small changes in loop direction can completely change the sorting order, making the algorithm flexible.
Program 5: Counting Sort as a reusable function
This version wraps Counting Sort in a clean, reusable function suitable for multiple datasets.
function countingSortUtility(arr) {
if (arr.length === 0) return arr;
let max = Math.max(...arr);
let count = Array(max + 1).fill(0);
for (let i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
let sorted = [];
for (let i = 0; i < count.length; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let data = [7, 3, 1, 4, 2, 7, 3];
console.log("Sorted array:", countingSortUtility(data));This function can be reused in any JavaScript project with integer arrays. Beginners will appreciate that Counting Sort can be neatly packaged into a utility function for practical use.
Frequently Asked Questions (FAQ)
This section answers common beginner questions about Counting Sort in JavaScript in a friendly way.
Q1. What is Counting Sort in JavaScript?
Counting Sort is a sorting algorithm that counts the occurrences of each number and arranges elements based on those counts.
Q2. When should Counting Sort be used?
It works best for integers or small-range numbers and is highly efficient when the range of input is not too large.
Q3. Can Counting Sort handle repeated numbers?
Yes, Counting Sort naturally handles repeated numbers by counting their occurrences.
Q4. Can Counting Sort sort in descending order?
Yes, simply iterate through the counting array in reverse to get descending order.
Q5. Is Counting Sort stable?
Yes, Counting Sort can be implemented to be stable, preserving the relative order of equal elements.
Conclusion
Counting Sort is a simple, fast, and efficient algorithm for sorting integers with a known range. It teaches beginners a different approach to sorting, focusing on counting occurrences rather than comparing elements.
Practicing Counting Sort helps beginners understand how to manipulate arrays, handle edge cases like zeros and duplicates, and implement efficient sorting algorithms in JavaScript. By experimenting with different datasets and orders, you can strengthen your algorithm skills and gain confidence in practical programming.




