|
| 1 | +import random |
| 2 | +from typing import List |
| 3 | + |
| 4 | +def bogo_sort(collection: List[int]) -> List[int]: |
| 5 | + """Pure implementation of the bogosort algorithm in Python. |
| 6 | + Bogosort generates random permutations until it guesses the correct one. |
| 7 | + |
| 8 | + More info on: https://en.wikipedia.org/wiki/Bogosort |
| 9 | + Args: |
| 10 | + collection (List[int]): A mutable ordered collection with comparable items. |
| 11 | + Returns: |
| 12 | + List[int]: The same collection ordered by ascending. |
| 13 | + Examples: |
| 14 | + >>> bogo_sort([0, 5, 3, 2, 2]) |
| 15 | + [0, 2, 2, 3, 5] |
| 16 | + >>> bogo_sort([]) |
| 17 | + [] |
| 18 | + >>> bogo_sort([-2, -5, -45]) |
| 19 | + [-45, -5, -2] |
| 20 | + Raises: |
| 21 | + ValueError: If the input is not a list of integers. |
| 22 | + Note: |
| 23 | + This is not an efficient sorting algorithm and is mainly used for educational purposes. |
| 24 | + For doctests, run the following command: |
| 25 | + python -m doctest -v bogo_sort.py |
| 26 | + or |
| 27 | + python3 -m doctest -v bogo_sort.py |
| 28 | + |
| 29 | + For manual testing, run: |
| 30 | + python bogo_sort.py |
| 31 | + """ |
| 32 | + |
| 33 | + def is_sorted(collection: List[int]) -> bool: |
| 34 | + for i in range(len(collection) - 1): |
| 35 | + if collection[i] > collection[i + 1]: |
| 36 | + return False |
| 37 | + return True |
| 38 | + |
| 39 | + while not is_sorted(collection): |
| 40 | + random.shuffle(collection) |
| 41 | + return collection |
| 42 | + |
| 43 | +if __name__ == "__main__": |
| 44 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 45 | + unsorted = [int(item) for item in user_input.split(",")] |
| 46 | + print(bogo_sort(unsorted)) |
0 commit comments