forked from heineman/LearningAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_sort.py
More file actions
24 lines (22 loc) · 736 Bytes
/
random_sort.py
File metadata and controls
24 lines (22 loc) · 736 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
"""Unusually poor sorting algorithms that work (eventually)."""
from random import shuffle
from itertools import permutations
from algs.sorting import check_sorted
def random_sort(A):
"""
Randomly shuffle A until it is sorted.
This can take arbitrarily long and may never actually
produce the sorted answer. However, with non-zero
probability it might generate the answer.
"""
while not check_sorted(A):
shuffle(A)
def permutation_sort(A):
"""
Generates all permutation of A until one is sorted.
Guaranteed to sort the values in A.
"""
for attempt in permutations(A):
if check_sorted(attempt):
A[:] = attempt[:] # copy back into A
return