Python Program for BogoSort or Permutation Sort
Last Updated :
28 Aug, 2023
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki)
Python Program for BogoSort or Permutation Sort
For example, if bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, one would throw the deck into the air, pick the cards up at random, and repeat the process until the deck is sorted.
PseudoCode:
while not Sorted(list) do
shuffle (list)
done
Python3
import random
def bogoSort(a):
n = len (a)
while (is_sorted(a) = = False ):
shuffle(a)
def is_sorted(a):
n = len (a)
for i in range ( 0 , n - 1 ):
if (a[i] > a[i + 1 ] ):
return False
return True
def shuffle(a):
n = len (a)
for i in range ( 0 ,n):
r = random.randint( 0 ,n - 1 )
a[i], a[r] = a[r], a[i]
a = [ 3 , 2 , 4 , 1 , 0 , 5 ]
bogoSort(a)
print ( "Sorted array :" )
for i in range ( len (a)):
print ( "%d" % a[i]),
|
Output
Sorted array :
0
1
2
3
4
5
Time Complexity:
Worst Case: O(∞) (since this algorithm has no upper bound)
Average Case: O(n*n!)
Best Case: O(n)(when the array given is already sorted)
Auxiliary Space: O(1)
BogoSort implementation using builtin shuffle() and sorted() function
In this implementation, the sorted built-in function is used to check if the list is sorted or not. The random.shuffle function is used to generate a permutation of the array a.
Python3
import random
def bogoSort(a):
n = len (a)
while not sorted (a) = = a:
random.shuffle(a)
a = [ 3 , 2 , 4 , 1 , 0 , 5 ]
bogoSort(a)
print ( "Sorted array:" )
for i in range ( len (a)):
print ( "%d" % a[i]),
|
Output
Sorted array:
0
1
2
3
4
5
Time Complexity:
Worst Case: O(∞) (since this algorithm has no upper bound)
Average Case: O(n*n!)
Best Case: O(n)(when the array given is already sorted)
Auxiliary Space: O(1)
Please refer complete article on BogoSort or Permutation Sort for more details!
Please Login to comment...