Tag Archives: Random

Shuffle an array in C

This is an implementation in C of the Fisher-Yates algorithm to randomly shuffle an array.

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

/* Get a random number >= first and <= second */
unsigned int rand_between(unsigned int first, unsigned int second)
{
    unsigned int range = second - first;
    return rand() % (range + 1) + first;
}

void shuffle(void* array, size_t num, size_t size)
{
    unsigned int i;
    void *temp = malloc(size);
    if (!temp) {
        return;
    }
    for (i = 0; i < num - 1; i++) {
        unsigned int j = rand_between(i, num - 1);
        if (i != j) {
            memcpy(temp, array + i * size, size);
            memcpy(array + i * size, array + j * size, size);
            memcpy(array + j * size, temp, size);
        }
    }
    free(temp);
}

Example program:

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

int main(void)
{
    char *elements[] = {"a", "b", "c", "d", "e"};
    const size_t size = sizeof(elements[0]);
    const size_t n = sizeof(elements) / size;
    char **shuffled;
    unsigned int i;

    shuffled = malloc(size * n);
    memcpy(shuffled, elements, size * n);
    srand(time(NULL));
    shuffle(shuffled, n, size);
    for (i = 0; i < n; i++) {
        printf("%s\n", shuffled[i]);
    }
    free(shuffled);
    return 0;
}