Last active
December 19, 2018 16:55
-
-
Save ankona/2fd9e80a68e0a07ae35dba833471ddb7 to your computer and use it in GitHub Desktop.
radix sorter
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
from pyqueue import PyQueue | |
def char_at(s, i): | |
if len(s) - 1 < i: | |
return " " | |
return s[i] | |
class RadixSort: | |
def __init__(self, words): | |
self.max_word_length = 0 | |
self.queue_list = [PyQueue() for x in range(0, 256)] | |
self.main_queue = PyQueue() | |
for word in words: | |
if len(word) > self.max_word_length: | |
self.max_word_length = len(word) | |
self.main_queue.enqueue(word) | |
def show_ordinal_queues(self): | |
for k, q in enumerate(self.queue_list): | |
if not q.is_empty(): | |
print(f"queue[{k}]: {q}") | |
def process(self): | |
for i in range(self.max_word_length-1, -1, -1): | |
print(f'processing letter {i}') | |
while not self.main_queue.is_empty(): | |
word = self.main_queue.dequeue() | |
char = char_at(word, i) | |
sort_queue_index = ord(char) | |
print(f'\t\tsort_queue_index of "{char}": {sort_queue_index}') | |
self.queue_list[sort_queue_index].enqueue(word) | |
print(f"\tself.main_queue: {self.main_queue}") | |
self.show_ordinal_queues() | |
for j in range(0, len(self.queue_list)): | |
queue = self.queue_list[j] | |
while not queue.is_empty(): | |
word = queue.dequeue() | |
self.main_queue.enqueue(word) | |
print(f"\tself.main_queue: {self.main_queue}") | |
result = [] | |
while not self.main_queue.is_empty(): | |
result.append(self.main_queue.dequeue()) | |
return result | |
def main(): | |
words = ['cat', 'hat', 'car', 'barn', 'farm', 'bat'] | |
sorter = RadixSort(words) | |
sorted_list = sorter.process() | |
print(sorted_list) | |
words = [] | |
# https://www.randomwordgenerator.com | |
with open('words.txt') as words_file: | |
for word in words_file: | |
words.append(word.strip()) | |
sorter = RadixSort(words) | |
sorted_list = sorter.process() | |
print(sorted_list) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment