-
Hajipur, Bihar, 844101
Counting Sort is a non-comparison-based sorting algorithm used to sort integers in a specific range.
It counts the number of occurrences of each element, then calculates positions to place them in sorted order.
It is efficient when the range of input data is not significantly greater than the number of items.
Count occurrences of each element
Store count in a separate array
Use that count to place each element at its correct position
Build the output array using the count array
def counting_sort(arr):
max_val = max(arr)
count = [0] * (max_val + 1)
# Count the frequency of each number
for num in arr:
count[num] += 1
# Reconstruct the sorted array
index = 0
for i in range(len(count)):
while count[i] > 0:
arr[index] = i
index += 1
count[i] -= 1
nums = [4, 2, 2, 8, 3, 3, 1]
counting_sort(nums)
print("Sorted array:", nums)
✅ Output:
Sorted array: [1, 2, 2, 3, 3, 4, 8]
Works only with non-negative integers
Not efficient if the range is too large compared to input size
Not suitable for floating point numbers or strings (without modification)
Case | Time |
---|---|
Best Case | O(n + k) |
Average | O(n + k) |
Worst Case | O(n + k) |
Space | O(k) |
Where
n
= number of elements,k
= range of input
Sorting test scores (0-100)
Sorting small-range integers
When stability and speed are more important than low space usage
Q1. Write a Python program to sort the list [3, 6, 4, 1, 3, 4, 1, 4]
using counting sort.
Q2. Write a Python program to modify counting sort so that it returns a new sorted array instead of modifying the original list.
Q3. Write a Python program to print the count array for the list [0, 2, 2, 3, 1]
using counting sort.
Q4. Write a Python program to handle counting sort on a list with values up to 1000.
Q5. Write a Python program to count and display how many times each number appears in the list using counting sort logic.
Q6. Write a Python program to accept a list of integers from user input and sort it using counting sort.
Q7. Write a Python program to sort a list that includes 0 using counting sort.
Q8. Write a Python program to attempt sorting a list with negative numbers using counting sort and observe what breaks.
Q9. Write a Python program to count and print the total number of iterations (loops) made during the counting sort process.
Q10. Write a Python program to compare the output of counting sort with Python's built-in sorted()
function for the same list.
Q1: What type of algorithm is counting sort?
Q2: Counting sort works best when:
Q3: Time complexity of counting sort is:
Q4: Counting sort is stable when:
Q5: What does the count array store?
Q6: Counting sort does not work well on:
Q7: Can Counting Sort be performed in-place?
Q8: What is a key requirement of input for counting sort?
Q9: What is the space complexity of counting sort?
Q10: Which of the following uses no comparison between elements?