Posted By

andrelaszlo on 07/14/11


Tagged

sorting bogosort


Versions (?)

Bogosort


 / Published in: Python
 

URL: http://en.wikipedia.org/wiki/Bogosort

Just for fun

  1. import random
  2.  
  3. def in_order(l):
  4. """Is the list sorted already?"""
  5. prev = None
  6. for i in l:
  7. if prev is not None:
  8. if i < prev:
  9. return False
  10. prev = i
  11. return True
  12.  
  13. def bogosort(l):
  14. """In place bogosort, best case: O(n), average O(n!), worst inf"""
  15. i = 0
  16. while not in_order(l):
  17. random.shuffle(l)
  18. i += 1
  19. return i
  20.  
  21. if __name__ == "__main__":
  22. n = 10
  23. l = list(range(n))
  24. random.shuffle(l)
  25. print "unsorted list:", l
  26. i = bogosort(l)
  27. print "sorted list (%s iterations): %s" % (i, str(l))

Report this snippet  

You need to login to post a comment.