
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for BogoSort or Permutation Sort
BogoSort, also known as Permutation Sort or Stupid Sort, is a sorting algorithm based on generating random permutations of the list until it gets sorted.
BogoSort continues to shuffle the array randomly until the list becomes sorted. The expected time complexity is unbounded, and its average performance is extremely poor.
Problem Statement
You are given a list of unsorted elements. Your task is to sort the list using BogoSort by repeatedly generating random permutations until the list is sorted.
Random Permutation-based Sorting
This sorting method checks if the list is sorted. If not, it randomly shuffles the elements and checks again. This process continues until the list is sorted.
Steps for BogoSort
- Check if the list is sorted.
- If not sorted, shuffle the list randomly.
- Repeat until the list is sorted.
Python Program for BogoSort or Permutation Sort
In this example, we use the random module to shuffle the list and repeatedly check if it is sorted -
import random # Function to check if list is sorted def is_sorted(arr): for i in range(len(arr) - 1): if arr[i] > arr[i + 1]: return False return True # Function to perform BogoSort def bogo_sort(arr): attempts = 0 while not is_sorted(arr): random.shuffle(arr) attempts += 1 print(f"Sorted after {attempts} shuffles") return arr # Test input arr = [3, 2, 1] sorted_arr = bogo_sort(arr) print(sorted_arr)
Following is the output obtained -
Sorted after 11 shuffles [1, 2, 3]
The array is randomly shuffled until it is sorted, which may take a long time even for small input.