|
| 1 | +""" |
| 2 | +A pure Python implementation of the Reverse Selection Sort algorithm. |
| 3 | +This algorithm progressively sorts the array by finding the largest |
| 4 | +element in each pass and placing it at the front. |
| 5 | +For doctests run following command: |
| 6 | +python3 -m doctest -v reverse_selection_sort.py |
| 7 | +For manual testing run: |
| 8 | +python3 reverse_selection_sort.py |
| 9 | +""" |
| 10 | + |
| 11 | + |
| 12 | +def reverse_selection_sort(collection: list) -> list: |
| 13 | + """ |
| 14 | + A pure implementation of reverse selection sort algorithm in Python |
| 15 | + :param collection: some mutable ordered collection with heterogeneous |
| 16 | + comparable items inside |
| 17 | + :return: the same collection sorted in descending order |
| 18 | + Examples: |
| 19 | + >>> reverse_selection_sort([45,23,11,89,54,1,3,36]) |
| 20 | + [89, 54, 45, 36, 23, 11, 3, 1] |
| 21 | + >>> reverse_selection_sort([0,-89,32,5,46,8,11]) |
| 22 | + [46, 32, 11, 8, 5, 0, -89] |
| 23 | + >>> reverse_selection_sort([34,-2,-1,98,-42]) |
| 24 | + [98, 34, -1, -2, -42] |
| 25 | + """ |
| 26 | + n = len(collection) |
| 27 | + for i in range(n - 1): |
| 28 | + # Find the maximum element in the unsorted portion |
| 29 | + max_idx = i |
| 30 | + for j in range(i + 1, n): |
| 31 | + if collection[j] > collection[max_idx]: |
| 32 | + max_idx = j |
| 33 | + |
| 34 | + # Swap the maximum element with the first element of the unsorted portion |
| 35 | + collection[i], collection[max_idx] = collection[max_idx], collection[i] |
| 36 | + |
| 37 | + return collection |
| 38 | + |
| 39 | + |
| 40 | +if __name__ == "__main__": |
| 41 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 42 | + unsorted = [int(item) for item in user_input.split(",")] |
| 43 | + print(reverse_selection_sort(unsorted)) |
0 commit comments