Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced B Tree in Data Structure Convert Sorted List to Binary Search Tree Flattening a Linked List Given a Perfect Binary Tree, Reverse Alternate Levels Left View of Binary Tree What are Forest Trees in Data Structure Compare Balanced Binary Tree and Complete Binary Tree Diameter of a Binary Tree Given a Binary Tree Check the Zig Zag Traversal Given a Binary Tree Print the Shortest Path Given a Binary Tree Return All Root To Leaf Paths Given a Binary Tree Swap Nodes at K Height Given a Binary Tree Find Its Minimum Depth Given a Binary Tree Print the Pre Order Traversal in Recursive Given a Generate all Structurally Unique Binary Search Trees Perfect Binary Tree Threaded Binary Trees

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 ).