Skip to content

Commit 495b4be

Browse files
authored
Merge pull request kelvins#327 from Hardvan/bogosort
Add Bogosort Algorithm in Python
2 parents 5570edc + 8ad75d2 commit 495b4be

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2638,8 +2638,8 @@ In order to achieve greater coverage and encourage more people to contribute to
26382638
</a>
26392639
</td>
26402640
<td> <!-- Python -->
2641-
<a href="./CONTRIBUTING.md">
2642-
<img align="center" height="25" src="./logos/github.svg" />
2641+
<a href="./src/python/bogosort.py">
2642+
<img align="center" height="25" src="./logos/python.svg" />
26432643
</a>
26442644
</td>
26452645
<td> <!-- Go -->

src/python/bogosort.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
# Example usage
35+
unsorted_list = [3, 1, 2, 5, 4]
36+
print("Unsorted list:", unsorted_list)
37+
38+
bogosort(unsorted_list)
39+
print("Sorted list:", unsorted_list)

0 commit comments

Comments
 (0)