forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbogo_sort.py
More file actions
38 lines (27 loc) · 800 Bytes
/
bogo_sort.py
File metadata and controls
38 lines (27 loc) · 800 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""
bogo_sort.py
Implementation of bogo sort on a list and returns a sorted list.
Bogo Sort Overview:
-------------------
A naive sorting that picks two elements at random and swaps them.
Time Complexity: O(n * n!)
Space Complexity: O(1) Auxiliary
Stable: No
WARNING: This algorithm may never sort the list correctly.
"""
import random
def sort(seq):
if len(seq) == 1:
return seq
random.seed()
while not is_sorted(seq):
if len(seq) == 2:
i = 0
j = 1
else:
i = random.randint(0, len(seq) - 2)
j = random.randint(i, len(seq) - 1)
seq[i], seq[j] = seq[j], seq[i]
return seq
def is_sorted(seq):
return all(seq[i - 1] <= seq[i] for i in xrange(1, len(seq)))