Shuffle an array in c

C program for Shuffle an array. Here more information.

// C Program 
// Shuffle the array elements
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

// Function which is swapping two array elements of given location
void swap_element(int arr[], int i, int j)
{
    //Get i location element
    int temp = arr[i];
    //set new values
    arr[i] = arr[j];
    arr[j] = temp;
}
// Function which is display array elements
void display(int arr[], int size)
{
    for (int i = 0; i < size; ++i)
    {
        printf(" %d ", arr[i]);
    }
    printf("\n");
}
// returns the random location of array elements
int random_location(int first, int last)
{
    // Calculate random number between given range
    return rand() % ((last) - first) + first;
}
// Function which is Shuffle given array elements
void shuffle_element(int arr[], int size)
{
    // [i] and [j] indicate locations
    int j = 0;
    int i = 0;
    // Variable which is controlling the execution process of loop
    int counter = 0;
    // Loop which is shuffling random elements in array
    while (counter < size)
    {
        // Get random location of array index
        i = random_location(0, size);
        j = random_location(0, size);
        if (i != j)
        {
            //swap array elements
            swap_element(arr, i, j);
            counter++;
        }
    }
}
int main()
{
    // impotant sets the seed based on the current time
    srand(time(NULL));
    // Define array elements
    int arr[] = {
        1,
        0,
        -3,
        8,
        7,
        3,
        9,
        4,
        2,
        5,
        10,
        6
    };
    //Get the size
    int size = sizeof(arr) / sizeof(arr[0]);
    //Before shuffling  array elements
    printf("Initial array elements\n");
    display(arr, size);
    printf("\nAfter Shuffle array elements\n");
    shuffle_element(arr, size);
    display(arr, size);
    shuffle_element(arr, size);
    display(arr, size);
    shuffle_element(arr, size);
    display(arr, size);
    return 0;
}

Output

Initial array elements
 1  0  -3  8  7  3  9  4  2  5  10  6

After Shuffle array elements
 5  -3  9  1  0  3  6  8  7  4  10  2
 8  4  9  7  3  0  6  1  5  -3  2  10
 -3  10  1  0  8  9  2  7  5  3  4  6


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved