|
| 1 | +""" |
| 2 | +This is pure python implementation of counting sort algorithm |
| 3 | +For doctests run following command: |
| 4 | +python -m doctest -v counting_sort.py |
| 5 | +or |
| 6 | +python3 -m doctest -v counting_sort.py |
| 7 | +For manual testing run: |
| 8 | +python counting_sort.py |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import print_function |
| 12 | + |
| 13 | + |
| 14 | +def counting_sort(collection): |
| 15 | + """Pure implementation of counting sort algorithm in Python |
| 16 | + :param collection: some mutable ordered collection with heterogeneous |
| 17 | + comparable items inside |
| 18 | + :return: the same collection ordered by ascending |
| 19 | + Examples: |
| 20 | + >>> counting_sort([0, 5, 3, 2, 2]) |
| 21 | + [0, 2, 2, 3, 5] |
| 22 | + >>> counting_sort([]) |
| 23 | + [] |
| 24 | + >>> counting_sort([-2, -5, -45]) |
| 25 | + [-45, -5, -2] |
| 26 | + """ |
| 27 | + # if the collection is empty, returns empty |
| 28 | + if collection == []: |
| 29 | + return [] |
| 30 | + |
| 31 | + # get some information about the collection |
| 32 | + coll_len = len(collection) |
| 33 | + coll_max = max(collection) |
| 34 | + coll_min = min(collection) |
| 35 | + |
| 36 | + # create the counting array |
| 37 | + counting_arr_length = coll_max + 1 - coll_min |
| 38 | + counting_arr = [0] * counting_arr_length |
| 39 | + |
| 40 | + # count how much a number appears in the collection |
| 41 | + for number in collection: |
| 42 | + counting_arr[number - coll_min] += 1 |
| 43 | + |
| 44 | + # sum each position with it's predecessors. now, counting_arr[i] tells |
| 45 | + # us how many elements <= i has in the collection |
| 46 | + for i in range(1, counting_arr_length): |
| 47 | + counting_arr[i] = counting_arr[i] + counting_arr[i-1] |
| 48 | + |
| 49 | + # create the output collection |
| 50 | + ordered = [0] * coll_len |
| 51 | + |
| 52 | + # place the elements in the output, respecting the original order (stable |
| 53 | + # sort) from end to begin, updating counting_arr |
| 54 | + for i in reversed(range(0, coll_len)): |
| 55 | + ordered[counting_arr[collection[i] - coll_min]-1] = collection[i] |
| 56 | + counting_arr[collection[i] - coll_min] -= 1 |
| 57 | + |
| 58 | + return ordered |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + import sys |
| 63 | + # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin |
| 64 | + # otherwise 2.x's input builtin function is too "smart" |
| 65 | + if sys.version_info.major < 3: |
| 66 | + input_function = raw_input |
| 67 | + else: |
| 68 | + input_function = input |
| 69 | + |
| 70 | + user_input = input_function('Enter numbers separated by a comma:\n') |
| 71 | + unsorted = [int(item) for item in user_input.split(',')] |
| 72 | + print(counting_sort(unsorted)) |
0 commit comments