Skip to content

Commit 10eb3f3

Browse files
committed
Add Bogosort Algorithm in Python
1 parent dce9bd9 commit 10eb3f3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/python/bogosort.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
""" Implementation of the bogosort algorithm in Python. """
2+
3+
import random
4+
5+
6+
def is_sorted(arr):
7+
"""Checks if an array is sorted.
8+
9+
Args:
10+
arr (list): The array to check.
11+
12+
Returns:
13+
bool: True if the array is sorted, False otherwise.
14+
"""
15+
return all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
16+
17+
18+
# Time: O(n * n!)
19+
# Space: O(1)
20+
def bogosort(arr):
21+
"""Sorts an array using the bogosort algorithm.
22+
23+
Args:
24+
arr (list): The array to sort.
25+
26+
Returns:
27+
None: The array is sorted in place.
28+
"""
29+
while not is_sorted(arr):
30+
random.shuffle(arr)
31+
32+
33+
if __name__ == "__main__":
34+
35+
# Example usage
36+
unsorted_list = [3, 1, 2, 5, 4]
37+
print("Unsorted list:", unsorted_list)
38+
39+
bogosort(unsorted_list)
40+
print("Sorted list:", unsorted_list)

0 commit comments

Comments
 (0)