Question: Counting Sort is a fast way to sort lists where the elements have a small number of possible values, such as integers within a certain

 Counting Sort is a fast way to sort lists where the

Counting Sort is a fast way to sort lists where the elements have a small number of possible values, such as integers within a certain range. Consider that if we are given a list of integers where the values are between 0 and 11, we can count and create a list of the number of times each value appears. For example, if our list of numbers is below: alon = [0, 0, 4, 7, 3, 3, 7, 7,7,9,11,11] We could write a function that computes a list of counts where the value at the ith index corresponds with how many times i appears in the original list: counts(alon) -> [2, 0, 0, 2, 1, 0, 0, 4, 0, 1,0,2] The output states that o appears 2 times, 3 appears 2 times, 4 appears 1 times, 7 appears 4 times, 9 appears once, and 11 appears twice in the original list. We could then write a function to produce a list containing the original values in order by iterating over each element in the count list and add it that many times as specified by the value at the ith index to the result list accumulator. The output list would now be: values (counts (alon)) -> [0, 0, 3, 3, 4, 7, 7, 7,7,9,11,11] Use the Design Recipe to write two functions: counts - consumes a list of values and produces a list of counts as described first above values - consumes a list of counts and returns the original list sorted in order as described second above Keep in mind that the input lists can have different maximum values so you cannot hard code the length of the accumulator list in your counts function. You can use [0]* (max(values)+1) to create the correct accumulator with all zeros for initial counts. For example: Test Result [2, 0, 0, 2, 1, 0, 0, 4, 0, 1) print (counts ( [0, 0, 4, 7, 3, 3, 7, 7, 7, 9])) print (counts ([10, 11, 14, 3, 13, 6, 3, 4, 8, 9, 10, 0, 2, 1, 16, 14])) [2, 1, 1, 2, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 2, 0, 1] print (values ([2,0,2,1])) print (values ( [2, 0,2,1,1,0,0, 2,5])) print (values (counts([4, 1, 4, 2, 3, 8, 1, 3, 4, 0]))) import random random_test_values = (random . randint (0,99) for x in range (1000)] print (values (counts (random_test_values)) == sorted (random_test_values)) [0, 0, 2, 2, 3] [O, 0, 2, 2, 3, 4, 7, 7, 8, 8, 8, 8, 31 [0, 1, 1, 2, 3, 4, 4, 4, 8, 81 True

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!