We need to implement counting sort for sorting integers in a specific range. The problem statement: "Implement counting sort for sorting integers in a specific range." So likely we need to write a function that sorts an array of integers using counting sort, given the range (maybe min and max). Or perhaps we need to handle the general case where we know the range (like 0 to k). We'll need to produce code in some language? Usually it's pseudocode or Python. Since the instruction doesn't specify, I'll write a Python implementation with explanation.
Counting sort is a non-comparative sorting algorithm that works by counting the number of occurrences of each distinct element in the input, then calculating the positions in sorted order. It assumes that the input elements are integers within a known range (e.g., 0 to k). Steps:
- Find the maximum value in the array to determine the range, or accept min and max as parameters.
- Create a count array of size k+1 (where k = max value) initialized to 0.
- Iterate over the input array and increment count for each value.
- Compute the cumulative sum over the count array to get positions (or directly use it for stable sorting).
- Iterate over the input array from the end to the beginning (for stability), place each element in its correct position in the output array, and decrement the cumulative count.
Alternatively, we can compute the output directly using counts and an auxiliary array.
We need to be careful about negative numbers? Counting sort typically works for non-negative integers. But we can handle negatives by offsetting with min value.
Thus we can implement a counting sort that works for any integer range by computing min and max.
Implementation details:
- Input: arr (list of integers)
- Output: sorted list (new list)
- Steps:
- If arr is empty: return []
- Determine min_val and max_val.
- Create offset = -min_val if min_val < 0 else 0, so that we can map value to index: index = value + offset.
- Create count array of size max_val - min_val + 1.
- Count occurrences.
- Compute prefix sums (cumulative counts) to get positions.
- Build output array of same length.
- Iterate from end to start over arr: for each value, index = value + offset; position = prefix[index] - 1; output[position] = value; prefix[index] -= 1.
- Return output.
That's the standard stable counting sort.
We could also use a simpler approach: compute counts, then generate sorted array by repeating each value count times. That is also counting sort but not stable? It's stable if we do it correctly? Actually generating by repeating values loses stability because we don't consider original order for equal elements, but stability is not required for sorting integers. However, typical counting sort algorithm described above is stable.
We'll provide an implementation in Python with function name counting_sort.
Now, we need to produce a solution explanation and code. The user asked "Implement counting sort for sorting integers in a specific range." Possibly they want a step-by-step algorithm or code. We'll give both.
I'll produce a response that includes:
- Explanation of counting sort and when it is used.
- Steps of the algorithm.
- Complexity analysis: O(n + k) time, O(n + k) space.
- Python code.
- Example usage.
Make sure to mention that it is efficient when the range of possible values (k) is not much larger than the number of elements (n).
Also, if the range is known (specific range), we can skip finding min and max and accept parameters.
I'll provide a function counting_sort(arr, min_val=None, max_val=None) where if not provided, we compute from arr.
But to keep it simple, just compute min and max.
Edge cases: empty list, negative numbers, duplicate values.
Now produce final answer.
Counting sort is an efficient, non‑comparative sorting algorithm that works well when the range of possible values (k) is not significantly larger than the number of elements (n). It counts the frequency of each distinct value and then uses those counts to place the elements directly into their correct positions.
Algorithm Steps
- Find the range: Determine the minimum and maximum values in the input array. If the range is known in advance, these can be provided as parameters.
- Create a count array: Allocate an array
count of size max_val - min_val + 1, all initialized to 0.
- Count frequencies: Iterate over the input array, incrementing
count[value - min_val] for each element.
- Compute cumulative sums: Modify
count so that each element at index i contains the number of elements less than or equal to the value corresponding to i. This step gives the starting index for each value in the sorted output.
- Build the output array: Create an output array of the same size as the input. Iterate over the input from end to beginning (to maintain stability). For each element:
- Compute its index in the count array:
idx = value - min_val.
- Place the element at position
count[idx] - 1 in the output array.
- Decrement
count[idx] by one.
- Return the sorted array.
Complexity
- Time: O(n + k), where n is the number of elements and k is the range (max - min + 1).
- Space: O(n + k) for the output and count arrays.
Python Implementation
def counting_sort(arr):
if not arr:
return []
# Step 1: Find the range
min_val = min(arr)
max_val = max(arr)
# Step 2: Initialize count array
range_of_vals = max_val - min_val + 1
count = [0] * range_of_vals
# Step 3: Count frequencies
for num in arr:
count[num - min_val] += 1
# Step 4: Convert counts to cumulative counts (positions)
for i in range(1, len(count)):
count[i] += count[i - 1]
# Step 5: Build the sorted array (stable)
output = [0] * len(arr)
for num in reversed(arr): # iterate backwards for stability
idx = num - min_val
output[count[idx] - 1] = num
count[idx] -= 1
return output
Example Usage
unsorted = [4, 2, -1, 0, 3, 2, 1]
sorted_arr = counting_sort(unsorted)
print(sorted_arr) # Output: [-1, 0, 1, 2, 2, 3, 4]
Notes
- The algorithm works for both positive and negative integers because it offsets the minimum value to zero.
- If the range of values is known and small, counting sort is extremely efficient, often outperforming comparison‑based sorts.
- Stability is preserved, which can be important when sorting composite objects by integer keys.
This implementation is self‑contained and handles all integer inputs within the constraints of available memory.