TheAlgorithms-Python
73 строки · 2.2 Кб
1"""
2This is pure Python implementation of counting sort algorithm
3For doctests run following command:
4python -m doctest -v counting_sort.py
5or
6python3 -m doctest -v counting_sort.py
7For manual testing run:
8python counting_sort.py
9"""
10
11
12def counting_sort(collection):13"""Pure implementation of counting sort algorithm in Python14:param collection: some mutable ordered collection with heterogeneous
15comparable items inside
16:return: the same collection ordered by ascending
17Examples:
18>>> counting_sort([0, 5, 3, 2, 2])
19[0, 2, 2, 3, 5]
20>>> counting_sort([])
21[]
22>>> counting_sort([-2, -5, -45])
23[-45, -5, -2]
24"""
25# if the collection is empty, returns empty26if collection == []:27return []28
29# get some information about the collection30coll_len = len(collection)31coll_max = max(collection)32coll_min = min(collection)33
34# create the counting array35counting_arr_length = coll_max + 1 - coll_min36counting_arr = [0] * counting_arr_length37
38# count how much a number appears in the collection39for number in collection:40counting_arr[number - coll_min] += 141
42# sum each position with it's predecessors. now, counting_arr[i] tells43# us how many elements <= i has in the collection44for i in range(1, counting_arr_length):45counting_arr[i] = counting_arr[i] + counting_arr[i - 1]46
47# create the output collection48ordered = [0] * coll_len49
50# place the elements in the output, respecting the original order (stable51# sort) from end to begin, updating counting_arr52for i in reversed(range(coll_len)):53ordered[counting_arr[collection[i] - coll_min] - 1] = collection[i]54counting_arr[collection[i] - coll_min] -= 155
56return ordered57
58
59def counting_sort_string(string):60"""61>>> counting_sort_string("thisisthestring")
62'eghhiiinrsssttt'
63"""
64return "".join([chr(i) for i in counting_sort([ord(c) for c in string])])65
66
67if __name__ == "__main__":68# Test string sort69assert counting_sort_string("thisisthestring") == "eghhiiinrsssttt"70
71user_input = input("Enter numbers separated by a comma:\n").strip()72unsorted = [int(item) for item in user_input.split(",")]73print(counting_sort(unsorted))74