Created
November 20, 2023 00:40
-
-
Save SLIB53/5f287b331c3eaa34c7e49a7828e271cd to your computer and use it in GitHub Desktop.
Sort strings using a radix sort
This file contains 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 order(string, pivot): | |
if pivot >= len(string): | |
return 0 | |
return ord(string[pivot]) - ord("a") + 1 | |
def sort_by_order(strings, pivot): | |
buckets = [None] * 27 | |
for i_buckets in range(len(buckets)): | |
buckets[i_buckets] = [] | |
for s in strings: | |
key = order(s, pivot) | |
buckets[key].append(s) | |
for b in buckets: | |
for s in b: | |
yield s | |
def sort(strings): | |
for p in range(10, -1, -1): | |
strings = list(sort_by_order(strings, p)) | |
return strings | |
case1 = ["apple", "orange", "banana", "app"] | |
print(sort(case1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment