简体   繁体   中英

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]] .

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

The problem is the line:

s_list.append([j] * helper_list[j])

This says to append a list ( [j]*helper_list[j] ) to s_list , adding that list as new element or s_list .

Instead, you want add one list onto the other, which can be done like so:

s_list.append += ([j] * helper_list[j])
def counting_sort(unordered_list, k, desc=False):
  '''
  unordered_list is the input array to be sorted.
  k is the range of non-negative key values.
  desc lets the algorithm to sort the array in descending order.
  time complexity is the sum of the times for two steps, O(n + k).
  '''
  count_list = [0] * k
  for element in unordered_list:
    count_list[element] += 1

  if desc:
    enumerator = reversed(list(enumerate(count_list)))
  else:
    enumerator = enumerate(count_list)

  sorted_list = []
  for idx, count in enumerator:
    sorted_list += [idx] * count

  return sorted_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM