How to Shuffle an array in C++
In this tutorial, we will solve how to shuffle a given array in C++ which is entered by the user. The size of the array and elements of the array we will take input from the user. We will create a function to shuffle the array of a given size which would take the array and array size as arguments. So, let’s see how to create the function.
Algorithm to create the shuffle function
- First, we will initialize stand() with NULL
- Then, we will traverse array from the back i.e. n-1
- Now, we will assign j with the random array index.
- Finally, swap the ith array element with the jth element which will shuffle the elements randomly
void shuffle (int arr[], int n)
{
srand (time (NULL));
for (int i = n - 1; i > 0; i--)
{
int j = rand () % i;
arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];
}
}
- Now, in the main function, we take input from the user.
- First, we will input the array size and then the array elements and then we call the shuffle() function
- At last print the array which is now shuffled. So, the whole code would look like as given below.
C++ Program to Shuffle an array
#include<iostream>
using namespace std;
void shuffle (int arr[], int n)
{
srand (time (NULL));
for (int i = n - 1; i > 0; i--)
{
int j = rand () % i;
arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];
}
}
int main ()
{
int arr[20], n, i;
cout << "Enter the size of array(max. 20): ";
cin >> n;
cout << "Enter the element of array :\n";
for (i = 0; i < n; i++)
cin >> arr[i];
shuffle (arr, n);
cout << "\nshuffled array:";
for (i = 0; i < n; i++)
cout << " " << arr[i];
return 0;
}
Output:
Enter the size of array(max. 20): 5 Enter the element of array : 1 2 3 4 5 shuffled array: 4 3 1 5 2
Note: In the given program to shuffle a given array in C++, it gives always different output for the same input.
Recommended Tutorial :
Leave a Reply