Counting Sort is a simple yet powerful sorting algorithm that works differently from comparison-based algorithms like Bubble Sort or Quick Sort. Instead of comparing elements, Counting Sort counts how many times each value appears in the input array. Using these counts, it then determines the correct position for each element in the sorted array. This approach makes it extremely fast when dealing with integers or items that can be mapped to numbers, especially when the range of values is not too large.
with hands-on learning.
get the skills and confidence to land your next move.
This algorithm matters because it is stable, predictable, and efficient for certain types of data. Counting Sort is often used in situations like sorting grades, scores, or other integer-based datasets where speed is important. For beginners learning TypeScript, it provides an easy way to understand how counting and positioning can be combined to sort an array without relying on repeated comparisons. In this article, we will go through several TypeScript programs that implement Counting Sort in different ways, including handling negative numbers and duplicates, so you can learn it thoroughly.
Program 1: Basic Counting Sort
This program shows the classic version of Counting Sort using an array of non-negative integers. It counts the occurrences of each number and builds a sorted array from the counts.
function countingSort(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
for (let num of arr) {
count[num]++;
}
let sorted: number[] = [];
for (let i = 0; i <= max; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let data: number[] = [4, 2, 2, 8, 3, 3, 1];
console.log("Sorted array:", countingSort(data));In this program, each element’s occurrence is counted, and then the counts are used to place elements in order. Beginners can visualize it as tallying marks for each number and then writing them out in sequence. This makes Counting Sort very intuitive and easy to implement.
Program 2: Counting Sort Using While Loops
This version implements the same logic using while loops to give beginners an alternative perspective on controlling the process.
function countingSortWhile(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
let i = 0;
while (i < arr.length) {
count[arr[i]]++;
i++;
}
let sorted: number[] = [];
let j = 0;
while (j <= max) {
while (count[j] > 0) {
sorted.push(j);
count[j]--;
}
j++;
}
return sorted;
}
let values: number[] = [5, 2, 3, 0, 2, 3, 1];
console.log("Sorted array:", countingSortWhile(values));This approach shows that Counting Sort can be implemented using different loop styles. Beginners can practice using while loops for control flow while understanding the core counting mechanism.
Program 3: Counting Sort for Large Numbers
Counting Sort works well for larger integers as long as the range is reasonable. This example demonstrates sorting an array of larger numbers.
function countingSort(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
for (let num of arr) {
count[num]++;
}
let sorted: number[] = [];
for (let i = 0; i <= max; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let largeNumbers: number[] = [50, 200, 150, 20, 80, 10];
console.log("Sorted array:", countingSort(largeNumbers));By simply adjusting the array, Counting Sort handles larger integers efficiently. Beginners can see that the algorithm scales with integer ranges and is still very straightforward to implement.
Program 4: Counting Sort with Duplicate Values
Counting Sort naturally handles duplicate values without any extra logic. This program demonstrates that behavior.
function countingSort(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
for (let num of arr) {
count[num]++;
}
let sorted: number[] = [];
for (let i = 0; i <= max; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let duplicates: number[] = [4, 1, 3, 4, 2, 1, 5];
console.log("Sorted array:", countingSort(duplicates));This example reassures beginners that Counting Sort is stable and will correctly sort arrays even when numbers are repeated multiple times.
Program 5: Counting Sort Using Functional Approach
This version uses modern TypeScript features like map and forEach for a cleaner and functional style implementation.
function countingSortFunctional(arr: number[]): number[] {
let max = Math.max(...arr);
let count = Array.from({ length: max + 1 }, () => 0);
arr.forEach(num => count[num]++);
let sorted: number[] = [];
count.forEach((c, i) => {
for (let j = 0; j < c; j++) {
sorted.push(i);
}
});
return sorted;
}
let numbers: number[] = [6, 3, 2, 8, 7, 2, 3];
console.log("Sorted array:", countingSortFunctional(numbers));This style shows beginners how Counting Sort can be implemented concisely and readably, while the underlying logic of counting and outputting remains unchanged.
Program 6: Counting Sort for Already Sorted Data
Counting Sort is efficient for arrays that are already sorted. This program demonstrates that scenario.
function countingSort(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
for (let num of arr) {
count[num]++;
}
let sorted: number[] = [];
for (let i = 0; i <= max; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let sortedData: number[] = [1, 2, 3, 4, 5, 6, 7];
console.log("Sorted array:", countingSort(sortedData));This shows that Counting Sort has predictable performance and works correctly even when the input does not require rearrangement.
Program 7: Counting Sort with Floating Point Numbers
By default, Counting Sort is designed for integers. For decimal numbers, they need to be scaled to integers.
function countingSort(arr: number[]): number[] {
let max = Math.max(...arr);
let count = new Array(max + 1).fill(0);
for (let num of arr) {
count[num]++;
}
let sorted: number[] = [];
for (let i = 0; i <= max; i++) {
while (count[i] > 0) {
sorted.push(i);
count[i]--;
}
}
return sorted;
}
let decimals: number[] = [0.5, 0.2, 0.8, 0.1];
let scaledDecimals = decimals.map(num => Math.floor(num * 10));
console.log("Sorted array:", countingSort(scaledDecimals).map(num => num / 10));This program helps beginners understand how to adapt Counting Sort to work with floating point numbers by scaling them into integers before sorting.
Program 8: Counting Sort for Negative Numbers
Negative numbers require shifting values so that all indices are positive. This program demonstrates that adjustment.
function countingSortWithNegatives(arr: number[]): number[] {
let min = Math.min(...arr);
let max = Math.max(...arr);
let range = max - min + 1;
let count = new Array(range).fill(0);
arr.forEach(num => count[num - min]++);
let sorted: number[] = [];
count.forEach((c, i) => {
for (let j = 0; j < c; j++) {
sorted.push(i + min);
}
});
return sorted;
}
let mixedNumbers: number[] = [-5, -1, 0, -3, 2, 1];
console.log("Sorted array:", countingSortWithNegatives(mixedNumbers));This shows beginners that Counting Sort can be extended to handle negative values by shifting the index range.
Frequently Asked Questions (FAQ)
This section answers common beginner questions about Counting Sort in TypeScript.
Q1. Can Counting Sort handle negative numbers?
Yes, but the algorithm needs adjustment to shift negative numbers to positive indices.
Q2. Is Counting Sort stable?
Yes, it preserves the order of equal elements, which is useful for sorting complex data.
Q3. Can Counting Sort handle decimals?
Yes, by scaling decimals to integers before sorting and scaling back afterward.
Q4. When is Counting Sort faster than other algorithms?
It is very fast when the range of numbers is not too large, especially compared to comparison-based sorts.
Q5. Is Counting Sort beginner-friendly?
Yes, it is intuitive because it uses counting instead of comparisons, which makes it easy to visualize and implement.
Conclusion
Counting Sort is a simple, fast, and stable sorting algorithm that works best with integer-based data. In this article, we explored multiple TypeScript programs implementing Counting Sort using loops, functional styles, and adjustments for negative and floating point numbers. Each example showed how beginners can understand the counting and placement logic clearly.
Practicing these programs will help you understand how Counting Sort works, and give you confidence in handling real-world datasets efficiently. By experimenting with duplicates, negatives, and decimals, beginners can gain a deep understanding of how versatile this algorithm can be in TypeScript.




