Python Program for BogoSort or Permutation Sort (original) (raw)

Last Updated : 4 Nov, 2025

BogoSort, also known as Permutation Sort, Stupid Sort, Slow Sort, Shotgun Sort, or Monkey Sort, is a highly inefficient sorting algorithm based on the generate-and-test paradigm. It repeatedly shuffles the elements of the list until it becomes sorted.

Algorithm:

  1. Start with an unsorted list of elements.
  2. Repeatedly shuffle the list randomly.
  3. After each shuffle, check if the list is sorted.
  4. Stop when the list becomes sorted.

Implementation of BogoSort

Python `

import random

def bogo_sort(arr): while True: sorted_flag = True for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: sorted_flag = False break

    if sorted_flag:
        break  

    n = len(arr)
    for i in range(n):
        r = random.randint(0, n - 1)
        arr[i], arr[r] = arr[r], arr[i]

arr = [3, 2, 4, 1, 0, 5] bogo_sort(arr) print("Sorted array:", *arr)

`

Output

Sorted array: 0 1 2 3 4 5

**Explanation:

BogoSort - Using Built-in Functions

A shorter version can be written using Python’s built-in sorted() and random.shuffle():

Python `

import random

def bogo_sort(arr): while arr != sorted(arr): random.shuffle(arr)

arr = [3, 2, 4, 1, 0, 5] bogo_sort(arr) print("Sorted array:", *arr)

`

Output

Sorted array: 0 1 2 3 4 5

**Explanation: