Pure implementation of counting sort algorithm in Python :param collection: some mutable ordered collection with heterogeneous comparable items inside :return: the same collection ordered by ascending Examples: >>> counting_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3, 5] >>> counti
(collection)
| 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 | def counting_sort_string(string): |
| 61 | return ''.join([chr(i) for i in counting_sort([ord(c) for c in string])]) |
no outgoing calls
no test coverage detected