Skip to content

Commit 86f3a3c

Browse files
authored
Merge pull request #101 from MuhammedKhamis/master
adding bogo sort
2 parents 17c5bff + af04f81 commit 86f3a3c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
2+
'''
3+
bogosort is a highly ineffective sorting function based on the generate and test paradigm. The function successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with more efficient algorithms.
4+
'''
5+
6+
7+
import random
8+
9+
10+
'''
11+
Random shuffle elements in the array, by swaping random 2 elements in each loop iteration.
12+
13+
'''
14+
def shuffle(array):
15+
for i in range(len(array)-1, -1, -1):
16+
j = random.randint(0, i)
17+
array[i], array[j] = array[j], array[i]
18+
19+
'''
20+
Checks if the array is sorted, by having non-decreasing sequence.
21+
22+
'''
23+
24+
def is_sorted(array):
25+
for i in range(len(array) - 1):
26+
if array[i] > array[i + 1]:
27+
return False
28+
return True
29+
30+
31+
'''
32+
__main__ function of the sort.
33+
34+
'''
35+
def bogosort(array):
36+
while not is_sorted(array):
37+
shuffle(array)
38+
return array

0 commit comments

Comments
 (0)