Skip to content

Instantly share code, notes, and snippets.

@jordanhudgens
Created May 29, 2014 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanhudgens/5ab113c555a5faa1a4d0 to your computer and use it in GitHub Desktop.
Save jordanhudgens/5ab113c555a5faa1a4d0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
def counting_sort(array, maxval):
"""in-place counting sort"""
m = maxval + 1
count = [0] * m # init with zeros
for a in array:
count[a] += 1 # count occurences
i = 0
for a in range(m): # emit
for c in range(count[a]): # - emit 'count[a]' copies of 'a'
array[i] = a
i += 1
return (array,count)
print counting_sort( [1, 4, 7, 2, 1, 3, 2, 1, 4, 2, 3, 2, 1], 7 )
# prints: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 7],[0, 4, 4, 2, 2, 0, 0, 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment