Shuffle a given array

Given an array of integers, this function will shuffle the given array. That is, it will shuffle the elements in the array randomly.

Example

INPUT:
arr[] = {4, 5, 6, 7, 8}

OUTPUT:
{6, 4, 8, 7, 5}

In this example, the output is just one of the possible outputs. Output will change every time we run this function

Time complexity: O(n)

Fisher-yates shuffle Agorithm:

1. Traverse the  array from end to  start

2. Take j, which is the random integer such that 0 <= j <= i

3. Swap arr[j], arr[i]

C++ Program

#include <bits/stdc++.h>
using namespace std;

int shuffle(int arr[], int n)
{
	srand ( time(NULL) ); //To not get the same output every time we run this program
	for (int i = n-1; i >= 0; --i)
	{
		int j = rand() % (i+1); //generating random number from 0 to i
		//Swaping the elements
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;

	}
	//Printing the shuffled array
	cout<<"shuffled array is [ ";
	for (int i = 0; i < n; ++i)
	{
		cout<<arr[i]<<" ";
	}
	cout<<"]"<<endl;
}
int main()
{
	
	int arr[]= {4, 5, 6, 7, 8};  //creating an array
    int n = sizeof(arr)/sizeof(arr[0]); //size of the array
    shuffle(arr,n);
    return 0;
}
Try It


Next > < Prev
Scroll to Top