Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

Counting Sort

Introduction to Counting Sort

Counting sort is a simple and efficient sorting algorithm that sorts a given list of integers by counting the occurrences of each element in the list. It is a non-comparative sorting algorithm, which means it doesn't compare the elements of the list during the sorting process. Counting sort works best for lists with a limited range of integer values, as it uses the integer values as indexes to count their occurrences.

Real-world Examples and Scenarios of Counting Sort

There are many real-world situations where counting sort can be employed to solve problems effectively. Some of these scenarios include:

Sorting exam scores: Imagine a teacher needs to sort the exam scores of a large class. Since the range of scores is limited (0 to 100, for example), counting sort can quickly sort the scores without comparing individual scores.

Organizing age demographics: In a city, the local government wants to analyze the age distribution of the population. With age ranges from 0 to 120, counting sort can be used to effectively sort the ages of individuals without needing to compare individual ages.

Election vote counting: During an election, the votes need to be counted for each candidate. Counting sort can be employed to efficiently count the votes for each candidate without comparing the votes themselves.

Technical Problem: Sorting Exam Scores

Let's consider the exam scores scenario. A teacher has recently conducted an exam for a course with 200 students. The scores for the exam range from 0 to 100. The teacher needs to sort the scores in ascending order to analyze the performance of the students and determine their grades.

Problem Statement

Given a list of integers representing the exam scores of 200 students, where each integer is in the range [0, 100], sort the list in ascending order using counting sort.

Real-world Scenario and Problem Statement

The problem of sorting exam scores can be solved using counting sort, as it effectively deals with sorting a list of integers with a limited range. By sorting the scores, the teacher can determine the performance of the students and assign grades accordingly.

Solution to the Problem: Counting Sort Algorithm

To solve the problem of sorting exam scores, we can implement the counting sort algorithm. The algorithm consists of the following steps:

  1. Create a counting array with a length equal to the range of the scores (0 to 100).
  2. Iterate through the input list and increment the count of each element in the counting array.
  3. Calculate the cumulative sum of the counting array.
  4. Iterate through the input list again and use the counting array to place the elements in the correct position in the sorted list.
  5. Return the sorted list.

Step by Step Solution with Real-world Scenario

Let's walk through the counting sort algorithm step by step, using the exam scores scenario:

Create a counting array with a length of 101 (0 to 100 scores).

Iterate through the list of exam scores (input list), and for each score, increment the count in the corresponding index of the counting array. For example, if the score is 75, increment the count at index 75.

Calculate the cumulative sum of the counting array. This gives us the position of each score in the sorted list.

Create a new list of the same length as the input list to store the sorted scores.

Iterate through the input list again, and for each score, place it in the correct position in the sorted list using the counting array. After placing the score, decrement the count in the counting array.

Return the sorted list.

Actual Code Solution with High-level Comments

Here's a Python implementation of the counting sort algorithm for the exam scores scenario:

def counting_sort(scores):
    # Step 1: Create a counting array with a length of 101 (0 to 100 scores).
    count_array = [0] * 101

    # Step 2: Iterate through the input list and increment the count of each element in the counting array.
    for score in scores:
        count_array[score] += 1

    # Step 3: Calculate the cumulative sum of the counting array.
    for i in range(1, len(count_array)):
        count_array[i] += count_array[i - 1]

    # Step 4: Create a new list of the same length as the input list to store the sorted scores.
    sorted_scores = [0] * len(scores)

    # Step 5: Iterate through the input list and use the counting array to place the elements in the correct position in the sorted list.
    for score in scores:
        sorted_scores[count_array[score] - 1] = score
        count_array[score] -= 1

    # Step 6: Return the sorted list.
    return sorted_scores

Calling the Function with Actual Values

Let's say we have the following exam scores for a class of 10 students:

exam_scores = [56, 78, 90, 45, 67, 83, 90, 76, 49, 62]

We can sort these scores using the counting_sort function:

sorted_exam_scores = counting_sort(exam_scores)
print(sorted_exam_scores)

Output:

[45, 49, 56, 62, 67, 76, 78, 83, 90, 90]

Explanation of the Code Solution with Intuitions and Analogies

In the counting sort algorithm, we first create a counting array to store the occurrences of each score. This is like creating a histogram of the scores, where each index of the counting array represents a score, and its value represents the number of occurrences of that score.

Next, we calculate the cumulative sum of the counting array, which gives us the position of each score in the sorted list. This is like adding up the occurrences of each score up to a certain point, which tells us how many scores are smaller than or equal to a particular score.

Finally, we use the counting array to place each score from the input list in the correct position in the sorted list. This is like using the histogram to put the scores in order, starting from the smallest score to the largest score.

How the Solution Can Solve Other Similar Real-world Problems

The counting sort algorithm can be applied to other real-world problems with similar characteristics as the exam scores scenario. For example:

In the age demographics scenario, the counting sort algorithm can be used to efficiently sort the ages of a population, making it easier to analyze the age distribution.

In the election vote counting scenario, the counting sort algorithm can be used to count the votes for each candidate without comparing the votes themselves, allowing for a quick and accurate tally of the election results.