×

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example:

Input-  { 2, 3, 0, 8, 4, 1, 7, 5, 6 }

Output- { 0, 1, 2, 3, 4, 5, 6, 7, 8 }

Explanation- We take an unsorted array and return the sorted array.

Algorithm:

Step 1: Start

Step 2: An array is created of size n. Then the value of the array size is taken from the user.

Step 3: The values of array elements are taken from the user.

Step 4: A function is called to calculate the answer.

Step 5: In this function, we take the array.

Step 6: This function processes all the array elements by permutation and sorts them.

Step 7: The answer is returned.

Step 8: The returned values will be printed.

Step 9: Stop.

Explanation of Algorithm: - So the basic concept behind this sorting algorithm is very simple and clear. We just have to do permutation. In the function, the numbers of the array will be permuted many times. After each permutation, it will be checked if the array is sorted or not. If the array is found sorted, the function returns the array or the permutation repeats.

Code:

Program in C++

// program in CPP to implement BOGO sort.
#include<bits/stdc++.h>
using namespace std;
bool sorted(int array[], int n)
{
	while ( n > 1 )
		if (array[n] < array[n-1])
			return false;
n--;
	return true;
}
void bn (int array[], int n)
{
	for (int i=0; i < n; i++)
		swap( array[i], array[rand() % n]);
}
void bogosort(int a[], int n)
{
	
	while ( !sorted(a, n) )
		bn(a, n);
}
int main()
{
	int a[] = { 2, 3, 0, 8, 4, 1, 7, 5, 6 };
	int n ;
cin>> n;
	bogosort(a, n);
	printf("Sorted array :\n");
	for (int i=0; i<n; i++)
		printf( "%d ", a[i]);
	printf("\n");


	return 0;
}

Program in Java:

// program in java to implement BOGO sort.
public class BogoS
{
	
	void bogoSort(int[] array)
	{
		
		while ( isSorted ( array ) == false)
			shuffle(array);
	}
	void shuffle(int[] a)
	{
		
		for (int i=1; i <= n; i++)
			swap(a, i, (int)(Math.random()*i));
	}
	void swap(int[] a, int i, int j)
	{
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	boolean isSorted(int[] array)
	{
		for (int i=1; i<array.length; i++)
			if (array[i] < array[i-1])
				return false;
		return true;
	}
	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)
	{
		
		int[] a = { 2, 3, 0, 8, 4, 1, 7, 5, 6 };
		BogoSort ob = new BogoSort();


		ob.bogoSort(a);


		System.out.print("Sorted array: ");
		ob.printArray(a);
	}
}

Program in C#:

// C# implementation of Bogo Sort
using System;
class jtp
{
	static void Swap<T>(ref T LHS, ref T RHS)
	{
		T temp;
		temp = 
LHS;
		LHS = RHS;
		RHS = temp;
	}
	
	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;
	}
		
	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)]);
	}
	
	public static void bogosort(int[] a, int n)
	{
		
		while ( !isSorted(a, n) )
			shuffle(a, n);
	}
	
	public static void printArray(int[] a, int n)
	{
		for (int i=0; i<n; i++)
			Console.Write(a[i] + " ");
		Console.Write("\n");
	}
	
	static void Main()
	{
		int[] a = {2, 3, 0, 8, 4, 1, 7, 5, 6};
		int n = a.Length;
		bogosort(a, n);
		Console.Write("Sorted array :\n");
		printArray(a,n);
	}
}

Program in Python:

# Program in python to implement BOGO sort.
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 = [2, 3, 0, 8, 4, 1, 7, 5, 6]
Bogost(a)
print("Sorted array :")
for i in range(len(a)):
	print ("%d" %a[i]),

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8]

Complexity Analysis: -

Time complexity-

  1. Best case: O (n) [when the array is sorted]
  2. Average case: O (n*n!)
  3. Worst case: O(8) [ the number of permutations may be infinite]

Space complexity-

Here, we need only constant memory. So, space complexity will be O ( 1 ).


Related Topics

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

Threaded Binary Trees

Introduction Threaded Binary Trees (TBTs) are an enhancement of normal binary trees intended for in-order traversal only. This means that this data structure is developed with the objective of making the...

12 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

What is Skewed Binary Tree

To understand the skewed binary tree, we must first understand the concept of a binary tree. A binary is generally the one in which every single node has two further...

3 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.

Bubble Sort in Data Structures

Bubble Sort in C++ The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order. Each iteration moves each member of the array...

4 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Vertical Order Traversal of Binary Tree

Implementation #include <iostream> #include <vector> #include <map> using namespace std; // representing the primary model of a binary tree node. struct _nod { int ky; _nod *Lft, *Rt; }; // establishing a new function representing the new binary tree node. struct _nod*...

5 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Given a Generate all Structurally Unique Binary Search Trees

Implementation // Creating a C++ program that will help us build all the binary search trees for the keys from 1 to n.  #include <bits/stdc++.h> using namespace std; // creating a structure that will...

8 minutes read.

Data Structures Algorithms

What is an Algorithm? An algorithm is a sequence of steps used to complete a job or get a desired result. It is similar to programming building elements that let cell...

4 minutes read.