Fisher–Yates shuffle

This algorithm produces an unbiased permutation: every permutation is equally likely.

Shuffling an array of n elements in C++:

void fisherYatesShuffling(int *arr, int n_elements)
{
    int shuffled_array[n_elements];
    int ind_taken[n_elements];
    for (int i = 0; i < n_elements; i++)
        ind_taken[i] = 0;
    int index;
 
    for (int i = 0; i < n; i++)
    {
        do
        {
            index = rand() % n_elements;
        }
        while (ind_taken[index] != 0);
 
        ind_taken[index] = 1;
        shuffled_array[i] = *(arr + index);
    }
    for (int i = 0; i < n_elements; i++)
    {
        cout << shuffled_array[i] << " ";
    }
}

Comments are closed, but trackbacks and pingbacks are open.