Counting Sort Algorithm in DSA C - Time & Space Complexity
Counting Sort is a special sorting method that works well when numbers are in a small range.
We want to know how the time it takes changes as the list size and number range grow.
Analyze the time complexity of the following code snippet.
void countingSort(int arr[], int n, int maxVal) {
int count[maxVal + 1];
for (int i = 0; i <= maxVal; i++)
count[i] = 0;
for (int i = 0; i < n; i++)
count[arr[i]]++;
int index = 0;
for (int i = 0; i <= maxVal; i++) {
while (count[i]-- > 0) {
arr[index++] = i;
}
}
}
This code sorts an array by counting how many times each number appears, then rebuilding the sorted array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Three loops: one to initialize counts, one to count elements, one to rebuild sorted array.
- How many times: First loop runs maxVal+1 times, second runs n times, third runs maxVal+1 times plus total n times inside inner while.
The time depends on both the number of elements (n) and the range of numbers (maxVal).
| Input Size (n) | Approx. Operations (with fixed maxVal=100) |
|---|---|
| 10 | About 10 + 101 + 10 = 121 |
| 100 | About 100 + 101 + 100 = 301 |
| 1000 | About 1000 + 101 + 1000 = 2101 |
Pattern observation: Operations grow roughly linearly with n plus the fixed range size.
| Range Size (maxVal) | Approx. Operations (with fixed n=100) |
|---|---|
| 10 | About 100 + 11 + 100 = 211 |
| 100 | About 100 + 101 + 100 = 301 |
| 1000 | About 100 + 1001 + 100 = 1201 |
Pattern observation: Operations grow linearly with the range size plus the number of elements.
Time Complexity: O(n + k)
This means the time grows linearly with the number of elements (n) plus the range of input values (k).
[X] Wrong: "Counting Sort always runs in linear time regardless of input range."
[OK] Correct: If the range (k) is very large compared to n, the time to initialize and process counts grows too, so it's not just about n.
Understanding Counting Sort's time helps you choose the right sorting method based on data size and range, a useful skill in many coding challenges.
"What if the input array contains negative numbers? How would the time complexity change if we adapt Counting Sort to handle them?"
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 in order
Using these counts, it places elements directly into the sorted output.Final Answer:
Counting the number of occurrences of each element to sort -> Option AQuick Check:
Counting occurrences = A [OK]
- Thinking it compares elements like bubble sort
- Confusing with divide and conquer methods
- Assuming it swaps elements repeatedly
max_val?Solution
Step 1: Understand array size for counts
The count array must hold counts for all values from 0 to max_val inclusive, so size is max_val + 1.Step 2: Choose correct declaration
Declaringint count[max_val + 1];ensures space for all possible values.Final Answer:
int count[max_val + 1]; -> Option AQuick Check:
Count array size = max_val + 1 [OK]
- Using max_val size misses last element count
- Using max_val - 1 causes out-of-range errors
- Using double size wastes memory unnecessarily
[4, 2, 2, 8, 3, 3, 1]?Solution
Step 1: Count occurrences of each element
1 appears once, 2 appears twice, 3 appears twice, 4 once, 8 once.Step 2: Place elements in sorted order using counts
Sorted array is [1, 2, 2, 3, 3, 4, 8].Final Answer:
[1, 2, 2, 3, 3, 4, 8] -> Option BQuick Check:
Sorted array = C [OK]
- Confusing input order with output order
- Forgetting to repeat elements by their counts
- Mixing up counts and positions
int count[5] = {0};
int arr[6] = {1, 3, 4, 2, 3, 0};
for (int i = 0; i < 6; i++) {
count[arr[i]]++;
}
for (int i = 0; i <= 5; i++) {
printf("%d ", count[i]);
}Solution
Step 1: Check count array size and loop range
Count array size is 5 (indices 0 to 4), but loop runs i from 0 to 5 inclusive, accessing count[5] which is out of bounds.Step 2: Identify out-of-bounds access
Accessing count[5] causes undefined behavior or error.Final Answer:
Loop accessing count array goes out of bounds -> Option DQuick Check:
Loop index > count size = D [OK]
- Ignoring array size when looping
- Assuming initialization fixes out-of-bounds
- Confusing arr size with count size
Solution
Step 1: Understand counting sort limitation
Counting sort works only with non-negative integers because it uses array indices as counts.Step 2: Adjust negative values for indexing
Shift all numbers by adding the absolute value of the minimum element to make all values non-negative before counting.Final Answer:
Shift all numbers by adding the absolute value of the minimum element before sorting -> Option CQuick Check:
Shift negatives to non-negative = B [OK]
- Trying to count negatives directly
- Ignoring negative values in input
- Switching to other sorts unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
