C implementation of the Fisher-Yates shuffle

This example C program implements the Fisher-Yates shuffle. It uses srandom and random for random numbers.

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

static void
print_pattern (int * pattern, int n)
{
    int i;
    for (i = 0; i < n; i++) {
	printf ("%d ", pattern[i]);
    }
    printf ("\n");
}

static void
shuffle (int * pattern, int n)
{
    int i;
    for (i = 0; i < n; i++) {
	pattern[i] = i;
    }
    print_pattern (pattern, n);
    for (i = n - 1; i > 0; i--) {
	int j;
	j = random () % (i+1);
	if (j != i) {
	    int swap;
	    swap = pattern[j];
	    pattern[j] = pattern[i];
	    pattern[i] = swap;
	}
    }
    print_pattern (pattern, n);
}

#define SIZE 20

int main ()
{
    int pattern[SIZE];
    srandom (time (0));
    shuffle (pattern, SIZE);
    return 0;
}

(download)

The output of the example looks like this:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
15 5 8 6 16 13 11 12 18 10 17 19 3 4 9 14 1 0 7 2 


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer