2016-08-04 18:07:45 +00:00
|
|
|
"""
|
2020-03-04 12:40:28 +00:00
|
|
|
This is a pure Python implementation of the bogosort algorithm,
|
|
|
|
also known as permutation sort, stupid sort, slowsort, shotgun sort, or monkey sort.
|
|
|
|
Bogosort generates random permutations until it guesses the correct one.
|
|
|
|
|
|
|
|
More info on: https://en.wikipedia.org/wiki/Bogosort
|
|
|
|
|
2016-08-04 18:07:45 +00:00
|
|
|
For doctests run following command:
|
2019-05-25 13:41:24 +00:00
|
|
|
python -m doctest -v bogo_sort.py
|
2016-08-04 18:07:45 +00:00
|
|
|
or
|
2019-05-25 13:41:24 +00:00
|
|
|
python3 -m doctest -v bogo_sort.py
|
2016-08-04 18:07:45 +00:00
|
|
|
For manual testing run:
|
2019-05-25 13:41:24 +00:00
|
|
|
python bogo_sort.py
|
2016-08-04 18:07:45 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
import random
|
|
|
|
|
2016-09-25 21:15:14 +00:00
|
|
|
|
2019-05-25 13:41:24 +00:00
|
|
|
def bogo_sort(collection):
|
2016-08-16 16:56:38 +00:00
|
|
|
"""Pure implementation of the bogosort algorithm in Python
|
2016-08-04 18:07:45 +00:00
|
|
|
:param collection: some mutable ordered collection with heterogeneous
|
|
|
|
comparable items inside
|
|
|
|
:return: the same collection ordered by ascending
|
|
|
|
Examples:
|
2019-05-25 13:41:24 +00:00
|
|
|
>>> bogo_sort([0, 5, 3, 2, 2])
|
2016-08-04 18:07:45 +00:00
|
|
|
[0, 2, 2, 3, 5]
|
2019-05-25 13:41:24 +00:00
|
|
|
>>> bogo_sort([])
|
2016-08-04 18:07:45 +00:00
|
|
|
[]
|
2019-05-25 13:41:24 +00:00
|
|
|
>>> bogo_sort([-2, -5, -45])
|
2016-08-04 18:07:45 +00:00
|
|
|
[-45, -5, -2]
|
|
|
|
"""
|
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
def is_sorted(collection):
|
2016-08-04 18:07:45 +00:00
|
|
|
if len(collection) < 2:
|
|
|
|
return True
|
2016-09-25 21:15:14 +00:00
|
|
|
for i in range(len(collection) - 1):
|
|
|
|
if collection[i] > collection[i + 1]:
|
2016-08-04 18:07:45 +00:00
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2020-03-04 12:40:28 +00:00
|
|
|
while not is_sorted(collection):
|
2016-09-25 21:15:14 +00:00
|
|
|
random.shuffle(collection)
|
2016-08-04 18:07:45 +00:00
|
|
|
return collection
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
|
|
|
unsorted = [int(item) for item in user_input.split(",")]
|
2019-05-25 13:41:24 +00:00
|
|
|
print(bogo_sort(unsorted))
|