Skip to content

Instantly share code, notes, and snippets.

@maurobaraldi
Created October 3, 2018 23:54
Show Gist options
  • Save maurobaraldi/a3f28767e667c2921e2a57ba862c86eb to your computer and use it in GitHub Desktop.
Save maurobaraldi/a3f28767e667c2921e2a57ba862c86eb to your computer and use it in GitHub Desktop.
Count Sort Python Implementation
def count_sort(array):
# The output character array that will have sorted arr
output = [0 for i in range(256)]
# Create a count array to store count of inidividul
# characters and initialize count array as 0
count = [0 for i in range(256)]
# For storing the resulting answer since the
# string is immutable
result = ["" for _ in array]
# Store count of each character
for i in array:
count[ord(i)] += 1
# Change count[i] so that count[i] now contains actual
# position of this character in output array
for i in range(250):
count[i] += count[i-1]
# Build the output character array
for i in range(len(array)):
output[count[ord(array[i])]-1] = array[i]
count[ord(array[i])] -= 1
# Copy the output array to arr, so that arr now
# contains sorted characters
for i in range(len(array)):
result[i] = output[i]
return result
assert ['_', 'c', 'n', 'o', 'o', 'r', 's', 't', 't', 'u'] == count_sort('count_sort')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment