Search code examples
pythonalgorithmsortingcounting-sort

Trouble implementing a counting sort algorithm


I'm trying to teach myself a few sorting algorithms in python and I'm having a little bit of trouble with the output. I'm attempting to implement a counting sort algorithm and I've gotten this far:

def counting_sort(l):
    nums = l
    highest = max(nums) + 1
    helper_list = [0] * highest
    s_list = []
    for i in range(len(nums)):
        value = nums[i]
        helper_list[value] += 1

    for j in range(len(helper_list)):
        s_list.append([j] * helper_list[j])

    return s_list

Everything is going almost fine, but when I give an input such as [5, 2, 2, 3, 1, 2].

I get an output like: [[], [1], [2, 2, 2], [3], [5]].


Solution

  • You just have to change the "append" for "extend". The append function adds an element to your list, in this case, another list. The extend function concatenates your list with the one given as a parameter.

    Your function should be like the following:

    def counting_sort(elements):
         highest = max(elements) + 1
         helper_list = [0] * highest
         s_list = []
         for value in elements:
             helper_list[value] += 1
    
         for j in range(len(helper_list)):
             s_list.extend([j] * helper_list[j])
    
         return s_list