From 93727c9a016aa874b7c3961e422f0fb953bfc1c1 Mon Sep 17 00:00:00 2001 From: William Zhang Date: Wed, 2 Oct 2019 18:46:12 -0400 Subject: [PATCH 1/2] added bogobogosort --- sorts/bogo_bogo_sort.py | 54 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 sorts/bogo_bogo_sort.py diff --git a/sorts/bogo_bogo_sort.py b/sorts/bogo_bogo_sort.py new file mode 100644 index 000000000000..0e512d8eea4f --- /dev/null +++ b/sorts/bogo_bogo_sort.py @@ -0,0 +1,54 @@ +""" +Python implementation of bogobogosort, a "sorting algorithm +designed not to succeed before the heat death of the universe +on any sizable list" - https://en.wikipedia.org/wiki/Bogosort. + +Author: WilliamHYZhang +""" + +import random + + +def bogo_bogo_sort(collection): + """ + returns the collection sorted in ascending order + :param collection: list of comparable items + :return: the list sorted in ascending order + + Examples: + >>> bogo_bogo_sort([0, 5, 3, 2, 2]) + [0, 2, 2, 3, 5] + >>> bogo_bogo_sort([-2, -5, -45]) + [-45, -5, -2] + >>> bogo_bogo_sort([420, 69]) + [69, 420] + """ + + def is_sorted(collection): + if len(collection) == 1: + return True + + clone = collection.copy() + while True: + random.shuffle(clone) + ordered = bogo_bogo_sort(clone[:-1]) + if clone[len(clone) - 1] >= max(ordered): + break + + for i in range(len(ordered)): + clone[i] = ordered[i] + + for i in range(len(collection)): + if clone[i] != collection[i]: + return False + return True + + while not is_sorted(collection): + random.shuffle(collection) + return collection + + +if __name__ == "__main__": + user_input = input("Enter numbers separated by a comma:\n").strip() + unsorted = [int(item) for item in user_input.split(",")] + print(bogo_bogo_sort(unsorted)) From 3b36097d1fc6830435a18fcef52c63166c4ae385 Mon Sep 17 00:00:00 2001 From: William Zhang Date: Wed, 2 Oct 2019 19:15:48 -0400 Subject: [PATCH 2/2] fix indentation error --- sorts/bogo_bogo_sort.py | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/sorts/bogo_bogo_sort.py b/sorts/bogo_bogo_sort.py index 0e512d8eea4f..f26a46e78645 100644 --- a/sorts/bogo_bogo_sort.py +++ b/sorts/bogo_bogo_sort.py @@ -11,18 +11,18 @@ def bogo_bogo_sort(collection): """ - returns the collection sorted in ascending order - :param collection: list of comparable items - :return: the list sorted in ascending order - - Examples: - >>> bogo_bogo_sort([0, 5, 3, 2, 2]) - [0, 2, 2, 3, 5] - >>> bogo_bogo_sort([-2, -5, -45]) - [-45, -5, -2] - >>> bogo_bogo_sort([420, 69]) - [69, 420] - """ + returns the collection sorted in ascending order + :param collection: list of comparable items + :return: the list sorted in ascending order + + Examples: + >>> bogo_bogo_sort([0, 5, 3, 2, 2]) + [0, 2, 2, 3, 5] + >>> bogo_bogo_sort([-2, -5, -45]) + [-45, -5, -2] + >>> bogo_bogo_sort([420, 69]) + [69, 420] + """ def is_sorted(collection): if len(collection) == 1: