
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implement Fisher-Yates Algorithm for Array Shuffling in C++
Fisher-Yates algorithm generates a random permutation of the array elements i.e. it randomly shuffles all the elements of an array. All the permutations for the array are equally likely as the Fisher-Yates algorithm is unbiased.
A program to implement the Fisher-Yates Algorithm for array shuffling in C++ is given as follows −
Example
#include <iostream> #include <t;stdlib.h> using namespace std; int main() { int n; cout << "Enter the array size: "<<endl; cin >> n; int arr[n], arr1[n], index_arr[n]; int index; cout << "Enter the array elements: "<<endl; for (int i = 0; i < n; i++) cin >> arr[i]; for (int i = 0; i < n; i++) index_arr[i] = 0; for (int i = 0; i < n; i++) { do { index = rand() % n; } while (index_arr[index] != 0); index_arr[index] = 1; arr1[i] = arr[index]; } cout<<"The shuffled array is: "; for (int i = 0; i < n; i++) cout << arr1[i] << " "; return 0; }
Output
The output of the above program is as follows
Enter the array size: 10 Enter the array elements: 1 2 3 4 5 6 7 8 9 10 The shuffled array is: 4 7 8 6 3 10 2 1 9 5
In the above program, the size of the array and the array are requested from the user. This is given below −
cout << "Enter the array size: "<<endl; cin >> n; int arr[n], arr1[n], index_arr[n]; int index; cout << "Enter the array elements: "<<endl; for (int i = 0; i < n; i++) cin >> arr[i];
After the array is obtained, index_arr[] is initialized to 0. Then the rand() function is used to randomly store the values of arr[] into arr1[]. This is demonstrated by the following code snippet −
for (int i = 0; i < n; i++) { do { index = rand() % n; } while (index_arr[index] != 0); index_arr[index] = 1; arr1[i] = arr[index]; }
Finally the shuffled array is displayed. This is seen below −
cout<<"The shuffled array is: "; for (int i = 0; i < n; i++) cout << arr1[i] << " ";
Advertisements