BogoSort or Permutation Sort
Last Updated :
11 Jul, 2023
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm one person can ever imagine. It is based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) 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.
Algorithm:
Bogo sort uses 2 steps to sort elements of the array.
1. It throws the number randomly.
2. Check whether the number is sorted or not.
3. If sorted then return the sorted array.
4. Otherwise it again generate another randomization of the numbers until the array is sorted.
PseudoCode:
while not Sorted(list) do
shuffle (list)
done
Example: Let us consider an example array ( 3 2 5 1 0 4 ) 4 5 0 3 2 1 (1st shuffling) 4 1 3 2 5 0 (2ndshuffling) 1 0 3 2 5 4 (3rd shuffling) 3 1 0 2 4 5 (4th shuffling) 1 4 5 0 3 2 (5th shuffling) . . . 0 1 2 3 4 5 (nth shuffling)------ Sorted Array Here, n is unknown because algorithm doesn’t know in which step the resultant permutation will come out to be sorted.
C++
// C++ implementation of Bogo Sort
#include <bits/stdc++.h>
using namespace std;
// To check if array is sorted or not
bool isSorted(int a[], int n)
{
while (--n > 0)
if (a[n] < a[n - 1])
return false;
return true;
}
// To generate permutation of the array
void shuffle(int a[], int n)
{
for (int i = 0; i < n; i++)
swap(a[i], a[rand() % n]);
}
// Sorts array a[0..n-1] using Bogo sort
void bogosort(int a[], int n)
{
// if array is not sorted then shuffle
// the array again
while (!isSorted(a, n))
shuffle(a, n);
}
// prints the array
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << "\n";
}
// Driver code
int main()
{
int a[] = { 3, 2, 5, 1, 0, 4 };
int n = sizeof a / sizeof a[0];
bogosort(a, n);
printf("Sorted array :\n");
printArray(a, n);
return 0;
}
Java
// Java Program to implement BogoSort
public class BogoSort {
// Sorts array a[0..n-1] using Bogo sort
void bogoSort(int[] a)
{
// if array is not sorted then shuffle the
// array again
while (isSorted(a) == false)
shuffle(a);
}
// To generate permutation of the array
void shuffle(int[] a)
{
// Math.random() returns a double positive
// value, greater than or equal to 0.0 and
// less than 1.0.
for (int i = 1; i < a.length; i++)
swap(a, i, (int)(Math.random() * i));
}
// Swapping 2 elements
void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// To check if array is sorted or not
boolean isSorted(int[] a)
{
for (int i = 1; i < a.length; i++)
if (a[i] < a[i - 1])
return false;
return true;
}
// Prints the array
void printArray(int[] arr)
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args)
{
// Enter array to be sorted here
int[] a = { 3, 2, 5, 1, 0, 4 };
BogoSort ob = new BogoSort();
ob.bogoSort(a);
System.out.print("Sorted array: ");
ob.printArray(a);
}
}
Python
# Python program for implementation of Bogo Sort
import random
# Sorts array a[0..n-1] using Bogo sort
def bogoSort(a):
n = len(a)
while (is_sorted(a) == False):
shuffle(a)
# To check if array is sorted or not
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1]):
return False
return True
# To generate permutation of the array
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]
# Driver code to test above
a = [3, 2, 4, 1, 0, 5]
bogoSort(a)
print("Sorted array :")
for i in range(len(a)):
print("%d" % a[i]),
C#
// C# implementation of Bogo Sort
using System;
class GFG {
// To Swap two given numbers
static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
// To check if array is sorted or not
public static bool isSorted(int[] a, int n)
{
int i = 0;
while (i < n - 1) {
if (a[i] > a[i + 1])
return false;
i++;
}
return true;
}
// To generate permutation of the array
public static void shuffle(int[] a, int n)
{
Random rnd = new Random();
for (int i = 0; i < n; i++)
Swap(ref a[i], ref a[rnd.Next(0, n)]);
}
// Sorts array a[0..n-1] using Bogo sort
public static void bogosort(int[] a, int n)
{
// if array is not sorted then shuffle
// the array again
while (!isSorted(a, n))
shuffle(a, n);
}
// prints the array
public static void printArray(int[] a, int n)
{
for (int i = 0; i < n; i++)
Console.Write(a[i] + " ");
Console.Write("\n");
}
// Driver code
static void Main()
{
int[] a = { 3, 2, 5, 1, 0, 4 };
int n = a.Length;
bogosort(a, n);
Console.Write("Sorted array :\n");
printArray(a, n);
}
// This code is contributed by DrRoot_
}
JavaScript
<script>
// Javascript program for implementation of Bogo sort
// To check if array is sorted or not
function isSorted(a, n){
for(var i = 1; i < arr.length; i++)
if (a[i] < a[i-1])
return false;
return true;
}
//swap function
function swap(arr, xp, yp){
var temp = arr[xp];
arr[xp] = arr[yp];
arr[yp] = temp;
}
// To generate permutation of the array
function shuffle(a, n){
var i, j=n;
for (i=0; i < n; i++){
var ind = Math.floor(Math.random() * n);
swap(a, j-i-1, ind);
}
return a;
}
// Sorts array a[0..n-1] using Bogo sort
function bogosort(a, n){
// if array is not sorted then shuffle
// the array again
while (!isSorted(a, n))
a = shuffle(a, n);
return a;
}
// prints the array
function printArray(arr, size){
var i;
for (i=0; i < size; i++)
document.write(arr[i]+ " ");
document.write("\n");
}
// Driver code
var arr = [3, 2, 5, 1, 0, 4];
var n = arr.length;
arr = bogosort(arr, n);
document.write("Sorted array: \n");
printArray(arr, n);
// This code is contributed by Susobhan Akhuli
</script>
OutputSorted 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 array given is already sorted)
Auxiliary Space: O(1)
Bozo Sort Algorithm:
Bozo sort is a variation of Bogo sort and is little more efficient than Bogo sort.
Check if the array is sorted or not.
Unlike bogo sort, if the list/array is not sorted then it picks only two items at random and swap them.
Then it checks if the array/list is sorted or not.
But like bogo sort, there is chance that it faces the same pseudo-random problems and it may never terminate.
It means it also has O(?) worst time complexity but its average case complexity is better than Bogo sort.
Question:
1. Tell the other names of Bogo sort?
Ans. Bogo sort has many other names like, permutation sort, slow sort, shotgun sort, stupid sort, bozo sort, blort sort, monkey sort, random sort or drunk man sort.
2. Why Bogo sort is called stupid sort, bozo sort, blort sort, monkey sort, random sort or drunk man sort?
Ans. Complexity of Bogo sort is O(?) since this algorithm has no upper bound. So, you can imagine how much inefficient this sorting algorithm is. That's why for its tremendous inefficiency, it is jokingly called stupid sort, bozo sort, blort sort, monkey sort, random sort or drunk man sort.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem