×

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

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Data Structure Prefix to Postfix Conversion

Prefix to Postfix Conversion Prefix: As the name suggests if the operator placed before the operands called the prefix expression.  The form of prefix expression is (operator, operand1, operand2). Example:  *+EF-GH (Infix:...

2 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Polish Notation in Data Structures

Arithmetic Expression: An arithmetic expression is defined as several operands or data items combined using several operators. For example; a+b*(c-d) is an expression. Operands: Operands represent the data in an expression...

2 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Convert Sorted List to Binary Search Tree

Implementation // creating the C++ implementation of the following approach: - #include <bits/stdc++.h> using namespace std; /* Create the link list node and see its implementation. */ class L__Nod { public: int record; L__Nod* next; }; /* constructing a new binary...

15 minutes read.