Skip to content

Instantly share code, notes, and snippets.

@appositum
Created September 3, 2021 23:47
Show Gist options
  • Save appositum/708bf3099281b466eaa0ff987df6dc16 to your computer and use it in GitHub Desktop.
Save appositum/708bf3099281b466eaa0ff987df6dc16 to your computer and use it in GitHub Desktop.
Counting Sort
import random
lst = [1, 4, 1, 2, 7, 5, 2]
def sort_count(lst):
# data ranges from 0 to 9
occ = [0 for i in range(10)]
# occurrences of each element
for _i, el in enumerate(lst):
occ[el] += 1
for i, el in enumerate(occ):
if i != 0:
occ[i] = el + occ[i-1]
res = [0 for i in range(len(lst))]
for el in lst:
res[occ[el] - 1] = el
occ[el] -= 1
return res
print(lst)
print(sort_count(lst))
random_lst = [random.randint(0, 9) for i in range(7)]
print()
print(random_lst)
print(sort_count(random_lst))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment