-
Notifications
You must be signed in to change notification settings - Fork 2
/
bogosort.c
66 lines (59 loc) · 1.5 KB
/
bogosort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* C Program to Implement BogoSort in an Integer Array
*/
#include <stdio.h>
#include <stdlib.h>
#define size 7
/* Function Prototypes */
int is_sorted(int *, int);
void shuffle(int *, int);
void bogosort(int *, int);
int main()
{
int numbers[size];
int i;
printf("Enter the elements of array:");
for (i = 0; i < size;i++)
{
scanf("%d", &numbers[i]);
}
bogosort(numbers, size);
printf("The array after sorting is:");
for (i = 0;i < size;i++)
{
printf("%d\n", numbers[i]);
}
printf("\n");
}
/* Code to check if the array is sorted or not */
int is_sorted(int *a, int n)
{
while (--n >= 1)
{
if (a[n] < a[n - 1])
{
return 0;
}
}
return 1;
}
/* Code to shuffle the array elements */
void shuffle(int *a, int n)
{
int i, t, temp;
for (i = 0;i < n;i++)
{
t = a[i];
temp = rand() % n; /* Shuffles the given array using Random function */
a[i] = a[temp];
a[temp] = t;
}
}
/* Code to check if the array is sorted or not and if not sorted calls the shuffle function to shuffle the array elements */
void bogosort(int *a, int n)
{
while (!is_sorted(a, n))
{
shuffle(a, n);
}
}