C++ Program for the BogoSort or Permutation Sort?


Bogosort simply shuffles a collection randomly until it is sorted. BogoSort is an ineffective algorithm based permutation and combination that's why it is known Permutation sort. BogoSort is very flop sorting technique which is also known as, shotgun sort, stupid sort, monkey sort, or slow sort. The algorithm successively generates permutations of its input until it finds one that is sorted.

Input - 53421
Output - 12345

Explanation

In bogosort array will be consist of unsorted element checking if the array elements are in order, and if it is not, then change the position of array elements, by swapping the elements randomly, and repeat the process until the array is sorted.

Example

#include <iostream>
#include <stdlib.h>
using namespace std;
int is_sorted(int *arr, int n) {
   while ( --n >= 1 ) {
      if ( arr[n] < arr[n-1] ) {
         return 0;
      }
   }
   return 1;
}
void shuffle(int *arr, int n) {
   int temp, r;
   for(int i=0; i < n; i++) {
      temp = arr[i];
      r = rand() % n;
      arr[i] = arr[r];
      arr[r] = temp;
   }
}
void bogosort(int *arr, int n) {
   while ( !is_sorted(arr, n) ) {
      shuffle(arr, n);
   }
}
int main() {
   int arr[] = { 5, 3, 4, 2, 1 };
   int i;
   bogosort(arr, 5);
   for (i=0; i < 5; i++) {
      cout<< arr[i]<<"\t";
   }
}

Updated on: 19-Aug-2019

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements