shuffle function in c

Solutions on MaxInterview for shuffle function in c by the best coders in the world

showing results for - "shuffle function in c"
Elena
18 Sep 2018
1#include <stdlib.h>
2
3/* Arrange the N elements of ARRAY in random order.
4   Only effective if N is much smaller than RAND_MAX;
5   if this may not be the case, use a better random
6   number generator. */
7void shuffle(int *array, size_t n)
8{
9    if (n > 1) 
10    {
11        size_t i;
12        for (i = 0; i < n - 1; i++) 
13        {
14          size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
15          int t = array[j];
16          array[j] = array[i];
17          array[i] = t;
18        }
19    }
20}
Filippo
07 Jul 2019
1#include <stdlib.h>
2
3void shuffle(int arr[], int size){
4    srand(time(0));
5    for (int i = 0; i < size; i++) {
6        int j = rand() % size;
7        int t = arr[i];
8        arr[i] = arr[j];
9        arr[j] = t;
10    }
11}