**Stay up to date**– embedded code automagically updates, each snippet and article has a feed Join Siafoo Now or Learn More

# Simple BogoSort implementation 0

In Brief | An implementation of the sweet BogoSort algorithm. Just download, run, and enjoy.... more |

Language | Python |

# 's

1from datetime import timedelta

2from random import shuffle

3from time import time

4

5def check_sort(ar):

6 for i in range(len(ar) - 1):

7 if ar[i] > ar[i + 1]:

8 return False

9

10 return True

11

12def bogo_sort(ar):

13

14 is_sorted = False

15 while not is_sorted:

16 is_sorted = check_sort(ar)

17

18 if is_sorted:

19 return ar

20

21 # Note that for even rather small len(ar), the total number of permutations of ar

22 # is larger than the period of most random number generators; this implies that

23 # most permutations of a long sequence can never be generated [from the Python Docs]

24 # What this means is that the algorithm may get stuck after a given array length

25 shuffle(ar)

26

27 return ar

28

29if __name__ == '__main__':

30

31 start = time()

32 print 'Sorting 1,2,3 ->', bogo_sort([1,2,3]), timedelta(seconds = time() - start)

33

34 start = time()

35 print 'Sorting 3,2,1 ->', bogo_sort([3,2,1]), timedelta(seconds = time() - start)

36

37 start = time()

38 print 'Sorting 3,4,5,6,7,1 ->', bogo_sort([3,4,5,6,7,1]), timedelta(seconds = time() - start)

39

An implementation of the sweet BogoSort algorithm. Just download, run, and enjoy.

Note that for even small len(ar), the total number of permutations of ar is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated [from the Python Docs] As such the algorithm may get stuck after a certain len(ar)

A sample run:

[stou@cipher src]$ python BogoSort.py Sorting 1,2,3 -> [1, 2, 3] 0:00:00.000145 Sorting 3,2,1 -> [1, 2, 3] 0:00:00.000126 Sorting 3,4,5,6,7,1,10,11,41,456,89 -> [1, 3, 4, 5, 6, 7, 10, 11, 41, 89, 456] 0:05:46.684337

## Comments

In the meantime, should I just stick with HTML tags, or raw-link things?