Skip to content

Instantly share code, notes, and snippets.

@nilskoppelmann
Last active July 17, 2016 17:26
Show Gist options
  • Save nilskoppelmann/7ececee1c72608be348a0f5954daee2b to your computer and use it in GitHub Desktop.
Save nilskoppelmann/7ececee1c72608be348a0f5954daee2b to your computer and use it in GitHub Desktop.
Counting Sort Python (for positive numbers only)
def counting_sort(a, mn, mx):
mx = max(a) if mx > max(a) else mx
count, result = [0] * (max(a) + 1), []
i, j = 0, mn
while i < len(a):
count[a[i]] += 1
i += 1
while j <= mx:
result += [j] * count[j]
j += 1
return result
a = [2, 9, 3, 8, 5, 43, 0, 1, 2]
print(counting_sort(a, 0, 22))
@nilskoppelmann
Copy link
Author

suggesting a different data-type to represent numbers including negative range
dictionary?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment