|
| 1 | +""" |
| 2 | +Python implementation of bogobogosort, a "sorting algorithm |
| 3 | +designed not to succeed before the heat death of the universe |
| 4 | +on any sizable list" - https://en.wikipedia.org/wiki/Bogosort. |
| 5 | +
|
| 6 | +Author: WilliamHYZhang |
| 7 | +""" |
| 8 | + |
| 9 | +import random |
| 10 | + |
| 11 | + |
| 12 | +def bogo_bogo_sort(collection): |
| 13 | + """ |
| 14 | + returns the collection sorted in ascending order |
| 15 | + :param collection: list of comparable items |
| 16 | + :return: the list sorted in ascending order |
| 17 | +
|
| 18 | + Examples: |
| 19 | + >>> bogo_bogo_sort([0, 5, 3, 2, 2]) |
| 20 | + [0, 2, 2, 3, 5] |
| 21 | + >>> bogo_bogo_sort([-2, -5, -45]) |
| 22 | + [-45, -5, -2] |
| 23 | + >>> bogo_bogo_sort([420, 69]) |
| 24 | + [69, 420] |
| 25 | + """ |
| 26 | + |
| 27 | + def is_sorted(collection): |
| 28 | + if len(collection) == 1: |
| 29 | + return True |
| 30 | + |
| 31 | + clone = collection.copy() |
| 32 | + while True: |
| 33 | + random.shuffle(clone) |
| 34 | + ordered = bogo_bogo_sort(clone[:-1]) |
| 35 | + if clone[len(clone) - 1] >= max(ordered): |
| 36 | + break |
| 37 | + |
| 38 | + for i in range(len(ordered)): |
| 39 | + clone[i] = ordered[i] |
| 40 | + |
| 41 | + for i in range(len(collection)): |
| 42 | + if clone[i] != collection[i]: |
| 43 | + return False |
| 44 | + return True |
| 45 | + |
| 46 | + while not is_sorted(collection): |
| 47 | + random.shuffle(collection) |
| 48 | + return collection |
| 49 | + |
| 50 | + |
| 51 | +if __name__ == "__main__": |
| 52 | + user_input = input("Enter numbers separated by a comma:\n").strip() |
| 53 | + unsorted = [int(item) for item in user_input.split(",")] |
| 54 | + print(bogo_bogo_sort(unsorted)) |
0 commit comments