C program for Bogo sort algorithm

C program for Bogo sort algorithm

426
5
SHARE

C program for Bogo sort algorithm : Bogosort Algorithm is also known as stupid sort or slow sort. Bogo sort is a particularly ineffective sorting algorithm based on the generate and test paradigm. It is not useful for sorting, but it is useful for educational purposes, to contrast it with other more realistic . It has also been used as an example in logic programming. If Bogosort is used to sort a deck of cards, it would consist of checking if the deck were in order, and if it were not, throwing the deck into the air, picking the cards up at random, and repeating the process until the deck is sorted. Let us see how to implement for Bogo sort algorithm.

C program for Bogosort Algorithm :

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <conio.h>

bool is_sorted(int *a, int n)
{
  while ( --n >= 1 ) {
    if ( a[n] < a[n-1] ) return false;
  }
  return true;
}

void shuffle(int *a, int n)
{
  int i, t, r;
  for(i=0; i < n; i++) {
    t = a[i];
    r = rand() % n;
    a[i] = a[r];
    a[r] = t;
  }
}

void bogosort(int *a, int n)
{
  while ( !is_sorted(a, n) ) shuffle(a, n);
}

int main()
{
  int numbers[20];
  int i,num;
  printf("\nEnter the number of elements in list : ");
  scanf("%d",&num);
  printf("\nEnter the elements of the list : \n");
  for(i=0;i<num;i++)
  {
                   scanf("%d",&numbers[i]);
                    }
  bogosort(numbers, num);
  printf("\nSorted list : \t");
  for (i=0; i < num; i++) printf("%d \t", numbers[i]);
  printf("\n");
  getch();
}

 

We hope you all have enjoyed the . If you have any queries ask us in form of comments.

 

5 COMMENTS

    • @ Eric
      Shuffle Logic :
      shuffle(int *a, int n)
      {
      int i, t, r;
      for(i=0; i < n; i++) { t = a[i]; r = rand() % n; a[i] = a[r]; a[r] = t; } } The above shuffle logic is as per requirement of Bogo sort. As bogo sort shuffling is equivalent to shuffling a deck of cards. So it didn't seems to be biased. Also I mentioned Bogo Sort as not useful because of its time complexity, also its a hit and trail method, so we cannot guarantee the actual time. As the number of elements to be sorted increase, its time of execution increases significantly. I hope this answers your query.. If you still have doubts, ask us in form of comments.

LEAVE A REPLY