Quick reference
Complexity | |
---|---|
Worst case time | |
Best case time | |
Average case time | |
Space |
Strengths:
- Linear time. Counting sort runs in time, making it asymptotically faster than comparison-based sorting algorithms like quicksort or merge sort.
Weaknesses:
- Restricted inputs. Counting sort only works when the range of potential items in the input is known ahead of time.
- Space cost. If the range of potential values is big, then counting sort requires a lot of space (perhaps more than ).
The High-Level Idea
Counting sort works by iterating through the input, counting the number of times each item occurs, and using those counts to compute an item's index in the final, sorted list.
Counting How Many Times Each Item Occurs
Say we have this list:
And say we know all the numbers in our list will be whole numbers between 0 and 10 (inclusive).
The idea is to count how many 0's we see, how many 1's we see, and so on. Since there are 11 possible values, we'll use a list with 11 counters, all initialized to 0.
Couldn't we use a dictionary instead? We could, but since we're working with items that can easily be mapped to list indices, using a list is a bit more lightweight. Remember: dictionaries are built on top of lists.
We'll iterate through the input once. The first item is a 4, so we'll add one to counts[4]. The next item is an 8, so we'll add one to counts[8].
And so on. When we reach the end, we'll have the total counts for each number:
Building the Sorted Output
Now that we know how many times each item appears, we can fill in our sorted list. Looking at counts, we don't have any 0's or 1's, but we've got two 2's. So, those go at the start of our sorted list.
No 3's, but there are two 4's that come next.
After that, we have one 6,
one 8,
and three 9's
And, with that, we're done!
Handling Non-Numeric Items
What if the items in our input aren't simple numbers that we can extract from our counts list?
As an example, what if we had a list of dessert objects, and we wanted to sort them by price?
We'll use these icons to represent the objects:
If we went through and counted up all the prices, we'd end up with the same counts list.
But when we go to add the 2's into our sorted list, we need to get the actual dessert objects.
There are a few ways we could do this:
- Iterate through the input to find both of the desserts that cost $2. That takes time for each cost, so time overall.
- Build a dictionary mapping prices to desserts. (Maybe this could even replace counts.) We could do this without adding any asymptotic time cost, but this would basically be making an extra copy of the input, which would be extra space.
We can do this in time without any extra copies of the input.
Building a Next Index List
Using our counts list, we can pre-compute where each item from the input should go. Then we'll just iterate through the input, using the pre-computed indices to place each item in the right spot.
We'll use our counts list to build up another list, next_index, that will track where the next occurrence of a price goes in our sorted output. For instance, next_index[4] would hold the index for the next item with a price of $4.
Hold up. Doesn't this add space to our algorithm?
Hang tight ... we'll see that with some cleverness we won't need a separate list for next_index after all.
We can initialize next_index from our counts list.
The lowest price is $2, so the $2 items will start at index 0. (Nothing costs $0 or $1, so we'll just set those to 0.)
Items that cost $3 go after all the items that cost $2. Two items in the list cost $2, so they'll take up indices 0 and 1. That means the first $3 item would go at index 2.
Notice how next_index[3] = next_index[2] + counts[2]. That makes sense, because we're taking the starting point for the $2 items and moving forward to make room for each of them. In general:
We can keep iterating through counts using this formula to fill in next_index.
As we'll see, we actually don't need counts anymore after we've built next_index.
So instead of creating a separate list for next_index, we can just modify counts in-place in one pass to get our next_index list. It's slightly trickier, but it can be done :)
Building Our Sorted list With next_index
First up, we've got
It has a price of $4. Since next_index[4] is 2, we know it goes at index 2.
And, since we've placed something at index 2, we now know that the next item that costs $4 goes after it, at index 3. So we'll increment next_index[4].
Moving on to the next item, we've got
It costs $8. Since next_index[8] is 5, it goes at index 5:
And we increment next_index[8]:
Next comes . It also costs $4, just like .
Good thing we incremented next_index[4] when we added to our sorted output! Else we'd just write our over at index 2 in our sorted output.
Speaking of, let's make sure we update next_index again:
Next up :
And we update next_index:
And so on, until we're done!
Implementation
Here's how we'd code it up:
What if the values could be negative? Or the smallest value was 50?
Our implementation assumes that all of the items are between 0 and some maximum. But it's pretty simple to extend the algorithm to handle any sort of range of integers. Give it a try. :)
Complexity
Counting sort takes time and space, where n is the number of items we're sorting and k is the number of possible values.
We iterate through the input items twice—once to populate counts and once to fill in the output list. Both iterations are time. Additionally, we iterate through counts once to fill in next_index, which is time.
The algorithm allocates three additional lists: one for counts, one for next_index, and one for the output. The first two are space and the final one is space.
You can actually combine counts and next_index into one list. No asymptotic changes, but it does save space.
In many cases cases, k is (i.e.: the number of items to be sorted is not asymptotically different than the number of values those items can take on. Because of this, counting sort is often said to be time and space.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!