Skip to content

Commit a6553e9

Browse files
authored
Create flashsort.py
1 parent e9e7c96 commit a6553e9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

sorts/flashsort.py

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

0 commit comments

Comments
 (0)