Skip to content

Commit c1e6955

Browse files
authored
Merge pull request #15 from naveenarun/patch-1
Create bogosort.py
2 parents c55eb1d + a2d2e4d commit c1e6955

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Diff for: sorts/bogosort.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
This is pure python implementation of bogosort algorithm
3+
For doctests run following command:
4+
python -m doctest -v bogosort.py
5+
or
6+
python3 -m doctest -v bogosort.py
7+
For manual testing run:
8+
python bogosort.py
9+
"""
10+
11+
from __future__ import print_function
12+
import random
13+
14+
def bogosort(collection):
15+
"""Pure implementation of bogosort algorithm in Python
16+
:param collection: some mutable ordered collection with heterogeneous
17+
comparable items inside
18+
:return: the same collection ordered by ascending
19+
Examples:
20+
>>> bogosort([0, 5, 3, 2, 2])
21+
[0, 2, 2, 3, 5]
22+
>>> bogosort([])
23+
[]
24+
>>> bogosort([-2, -5, -45])
25+
[-45, -5, -2]
26+
"""
27+
28+
def isSorted(collection):
29+
if len(collection) < 2:
30+
return True
31+
for i in range(len(collection)-1):
32+
if collection[i] > collection[i+1]:
33+
return False
34+
return True
35+
36+
while not isSorted(collection):
37+
random.shuffle(collection)
38+
return collection
39+
40+
if __name__ == '__main__':
41+
import sys
42+
43+
# For python 2.x and 3.x compatibility: 3.x has not raw_input builtin
44+
# otherwise 2.x's input builtin function is too "smart"
45+
if sys.version_info.major < 3:
46+
input_function = raw_input
47+
else:
48+
input_function = input
49+
50+
user_input = input_function('Enter numbers separated by coma:\n')
51+
unsorted = [int(item) for item in user_input.split(',')]
52+
print(bogosort(unsorted))

0 commit comments

Comments
 (0)