C++ Program for BogoSort or Permutation Sort?

C++Server Side ProgrammingProgramming

Here we will see another sorting algorithm called the Bogo Sort. This sort is also known as Permutation sort, Stupid sort, slow sort etc. This sorting algorithm is particularly ineffective sorting technique. This comes under the generate and test paradigm. It repeatedly generates a permutation until it is sorted. The conception is very straight forward. Until the list is sorted just shuffle the elements.

Algorithm

bogoSort(array, n)

Begin
   while the arr is not sorted, do
      shuffle arr
   done
End

Example

#include<iostream>
#include<cstdlib>
using namespace std;
bool isSorted(int arr[], int n) { //check whether the list is sorted
   or not
   while (--n > 1)
      if (arr[n] < arr[n - 1])
   return false;
return true;
}
void shuffle(int arr[], int n) {
   for (int i = 0; i < n; i++)
      swap(arr[i], arr[rand() % n]);
}
void bogoSort(int arr[], int n){
   while (!isSorted(arr, n))
      shuffle(arr, n);
}
main() {
   int data[] = {54, 74, 98, 5, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   bogoSort(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}

Output

Sorted Sequence 5 13 20 32 35 40 54 74 98 98
raja
Published on 31-Jul-2019 12:38:27
Advertisements