This C program implements Fisher-Yates algorithm for array shuffling. cycles of length n instead. The Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.
Here is the source code of the C program to shuffle an array using Fisher-Yates algorithm. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
static int rand_int(int n) {
int limit = RAND_MAX - RAND_MAX % n;
int rnd;
do {
rnd = rand();
}
while (rnd >= limit);
return rnd % n;
}
void shuffle(int *array, int n) {
int i, j, tmp;
for (i = n - 1; i > 0; i--) {
j = rand_int(i + 1);
tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
int main(void)
{
int i = 0;
int numbers[50];
for (i = 0; i < 50; i++)
numbers[i]= i;
shuffle(numbers, 50);
printf("\nArray after shuffling is: \n");
for ( i = 0; i < 50; i++)
printf("%d\n", numbers[i]);
return 0;
}
$ gcc fisher_yates.c -o fisher_yates $ ./fisher_yates Array after shuffling is: 26 41 32 18 45 48 8 35 44 31 10 30 24 1 12 13 40 0 43 47 27 42 4 14 49 36 6 19 5 11 7 37 34 28 21 46 38 20 16 2 17 15 3 22 25 29 23 9 39 33
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Reference Books in C Programming, Data Structures and Algorithms.