Created
August 31, 2018 00:08
-
-
Save umluizlima/ca95819f620571ebdcfb47cd53e181db to your computer and use it in GitHub Desktop.
Counting Sort implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Counting sort implementation. | |
This module implements the counting_sort function. | |
>>> counting_sort([1, 4, 1, 2, 7, 5, 2]) | |
[1, 1, 2, 2, 4, 5, 7] | |
""" | |
def counting_sort(l: list) -> list: | |
"""Return the sorted version of l. | |
>>> counting_sort([102, 85, 94]) | |
[85, 94, 102] | |
""" | |
# create an aux list with length of max(l)+1 | |
aux = [0] * (max(l)+1) | |
# store the number of repetitions of l's elements in aux | |
for i in l: | |
aux[i] += 1 | |
# sum each aux's element with its predecessor | |
for i in range(1, len(aux)): | |
aux[i] += aux[i-1] | |
# fill res with l's elements in the correct positions | |
res = [None] * len(l) | |
for i in l: | |
res[aux[i]-1] = i | |
aux[i] -=1 | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment