What if you could sort thousands of items instantly just by counting them first?
Why Counting Sort Algorithm in DSA C++?
Imagine you have a big box of colored balls, and you want to arrange them by color quickly. If you try to pick each ball and compare it with every other ball to find its place, it will take a very long time.
Sorting by comparing each ball to others is slow and tiring. It can take a lot of time, especially if you have many balls. Also, it is easy to make mistakes when comparing many items one by one.
Counting Sort solves this by counting how many balls of each color you have first. Then, it uses these counts to place each ball directly in the right order without comparing them one by one. This makes sorting very fast and simple.
for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { std::swap(arr[i], arr[j]); } } }
int count[maxValue + 1] = {0}; for (int i = 0; i < n; i++) { count[arr[i]]++; } int index = 0; for (int i = 0; i <= maxValue; i++) { while (count[i]-- > 0) { arr[index++] = i; } }
Counting Sort enables lightning-fast sorting when you know the range of values, making tasks like organizing or searching much easier.
Think about sorting exam scores from 0 to 100. Counting Sort quickly counts how many students got each score and then lists the scores in order without comparing each student's score to others.
Manual comparison sorting is slow and error-prone for large data.
Counting Sort counts occurrences to sort efficiently without direct comparisons.
This method is perfect when sorting numbers within a known small range.
Practice
Counting Sort Algorithm?Solution
Step 1: Understand Counting Sort principle
Counting sort counts how many times each value appears in the input.Step 2: Use counts to place elements
These counts help to place each element directly into the sorted output without comparisons.Final Answer:
Count the occurrences of each element and use counts to place elements in order -> Option AQuick Check:
Counting occurrences = Count the occurrences of each element and use counts to place elements in order [OK]
- Thinking counting sort compares elements
- Confusing counting sort with merge sort
- Assuming counting sort works on any data type
Solution
Step 1: Determine size of count array
Input values range from 0 to 9, so we need 10 slots (0 through 9).Step 2: Declare count array with size 10
Usingint count[10] = {0};initializes all counts to zero for indices 0 to 9.Final Answer:
int count[10] = {0}; -> Option BQuick Check:
Array size = max value + 1 = 10 [OK]
- Using size 9 instead of 10
- Not initializing count array to zero
- Declaring count array without size
arr = {4, 2, 2, 8, 3, 3, 1}?
void countingSort(int arr[], int n) {
int output[n];
int count[9] = {0};
for (int i = 0; i < n; i++)
count[arr[i]]++;
for (int i = 1; i < 9; i++)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
countingSort(arr, n);
for (int i = 0; i < n; i++)
std::cout << arr[i] << " ";
return 0;
}Solution
Step 1: Count frequencies and cumulative counts
Count array after counting: count[1]=1, count[2]=2, count[3]=2, count[4]=1, count[8]=1; cumulative sums give positions.Step 2: Place elements in output using counts
Elements placed in output array in sorted order: 1 2 2 3 3 4 8.Final Answer:
1 2 2 3 3 4 8 -> Option DQuick Check:
Sorted array = 1 2 2 3 3 4 8 [OK]
- Not using cumulative counts correctly
- Placing elements in wrong order
- Using wrong count array size
void countingSort(int arr[], int n) {
int output[n];
int count[10] = {0};
for (int i = 0; i <= n; i++)
count[arr[i]]++;
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}Solution
Step 1: Check loop bounds in counting frequencies
The first for loop uses i <= n, which accesses arr[n] out of bounds (indexing error).Step 2: Fix loop condition to i < n
Changing to i < n prevents out-of-bounds access and correctly counts frequencies.Final Answer:
Change loop to for (int i = 0; i < n; i++) in first for loop -> Option CQuick Check:
Loop bounds must be less than n to avoid errors [OK]
- Using <= n instead of < n in loops
- Ignoring array out-of-bounds errors
- Changing unrelated loops unnecessarily
arr = {5, 3, 0, 2, 3, 5, 1, 4} with values ranging from 0 to 5, how would you modify the counting sort algorithm to sort this array in descending order?Solution
Step 1: Understand normal counting sort placement
Normal counting sort places elements from lowest to highest using cumulative counts.Step 2: Modify placement to iterate from highest to lowest
To sort descending, iterate counts from max to min and place elements accordingly in output.Final Answer:
After computing cumulative counts, iterate from highest to lowest index to place elements in output -> Option AQuick Check:
Reverse iteration in placement = descending sort [OK]
- Just reversing input without changing counting logic
- Using other sorting algorithms instead of modifying counting sort
- Reversing output after sorting without adjusting counts
Ready to prove it?
Pass the test and this pattern moves unknown
