# C program to implement Bogo sort algorithm

Here, we are going to learn how to implement Bogo sort algorithm using C program?
Submitted by Nidhi, on August 17, 2021

Problem Solution:

Here, we will create an array of integers then we will read array elements from the user and implement the Bogo sort algorithm to arrange array elements in ascending order.

Program:

The source code to implement the Bogo sort algorithm is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to implement Bogo sort algorithm

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

int isSorted(int* arr, int len)
{
len = len - 1;
while (len > 0) {
if (arr[len] < arr[len - 1])
return 0;
len--;
}
return 1;
}

void shuffle(int* arr, int len)
{
int i = 0;
int t = 0;

int temp = 0;

while (i < len) {
t = arr[i];

temp = rand() % len;
arr[i] = arr[temp];
arr[temp] = t;

i++;
}
}

void bogoSort(int* arr, int len)
{
while (!isSorted(arr, len))
shuffle(arr, len);
}

int main()
{
int i = 0;
int arr[7];

printf("Enter array elements:\n");
while (i < 7) {
printf("Element[%d]: ", i);
scanf("%d", &arr[i]);
i++;
}

bogoSort(arr, 7);

printf("Sorted Array: \n");
i = 0;
while (i < 7) {
printf("%d ", arr[i]);
i++;
}
printf("\n");

return 0;
}
```

Output:

```RUN 1:
Enter array elements:
Element[0]: 20
Element[1]: 15
Element[2]: 5
Element[3]: 10
Element[4]: 30
Element[5]: 45
Element[6]: 2
Sorted Array:
2 5 10 15 20 30 45

RUN 2:
Enter array elements:
Element[0]: 24
Element[1]: 98
Element[2]: 45
Element[3]: 87
Element[4]: 28
Element[5]: 45
Element[6]: 67
Sorted Array:
24 28 45 45 67 87 98
```

Explanation:

Here, we created four functions isSorted(), shuffle(), bogoSort(), and main(). The isSorted() function is used to check array is sorted or not. The shuffle() function is used to shuffle array elements for sorting. The bogoSort() function is used to sort array elements.

In the main() function, we read array elements from the user. Then we sorted the elements of the array in ascending order using the bogoSort() function and print the sorted array on the console screen.

Preparation

What's New

Top Interview Coding Problems/Challenges!