-
-
Notifications
You must be signed in to change notification settings - Fork 50.3k
Expand file tree
/
Copy pathbozo_sort.py
More file actions
50 lines (36 loc) · 1.24 KB
/
bozo_sort.py
File metadata and controls
50 lines (36 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
This is a pure Python implementation of the bozosort algorithm.
Bozosort chooses two elements at random and swaps them. It does
this repeatedly until the list is sorted.
For more info, check "Bozosort": https://en.wikipedia.org/wiki/Bogosort#Related_algorithms
For doctests run following command:
python -m doctest -v bozo_sort.py
or
python3 -m doctest -v bozo_sort.py
For manual testing run:
python bozo_sort.py
"""
import random
def bozo_sort(array: list) -> list:
"""
Pure Python implementation of the bozosort algorithm.
Examples:
>>> bozo_sort([1, 14, 20, 9, 5])
[1, 5, 9, 14, 20]
>>> bozo_sort([8, 16, 0, 4, 10])
[0, 4, 8, 10, 16]
"""
def is_sorted(array: list) -> bool:
for i, n in enumerate(array):
if i < len(array) - 1 and n > array[i + 1]:
return False
return True
while not is_sorted(array):
index_a = random.randint(0, len(array) - 1)
index_b = random.randint(0, len(array) - 1)
array[index_a], array[index_b] = array[index_b], array[index_a]
return array
if __name__ == "__main__":
user_array = input("Enter numbers separated by spaces: ")
unsorted = [int(i) for i in user_array.split(" ")]
print(bozo_sort(unsorted))