Created
October 3, 2018 23:54
-
-
Save maurobaraldi/a3f28767e667c2921e2a57ba862c86eb to your computer and use it in GitHub Desktop.
Count Sort Python Implementation
This file contains hidden or 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
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