 # C++ Programming Code Examples

## C++ > Mathematics Code Examples

### Program to Implement Fisher-Yates Algorithm for Array Shuffling

``` Program to Implement Fisher-Yates Algorithm for Array Shuffling This is a C++ Program to shuffle array using Fisher-Yates algorithm. The Fisher-Yates shuffle (named after Ronald Fisher and Frank Yates), also known as the Knuth shuffle (after Donald Knuth), is an algorithm for generating a random permutation of a finite set-in plain terms, for randomly shuffling the set. A variant of the Fisher-Yates shuffle, known as Sattolo's algorithm, may be used to generate random cycles of length n instead. The Fisher-Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space. #include <iostream> #include <stdlib.h> using namespace std; void fisherYatesShuffling(int *arr, int n) { int a[n]; int ind[n]; for (int j = 0; j < n; j++) ind[j] = 0; int index; for (int j = 0; j < n; j++) { do { index = rand() % n; } while (ind[index] != 0); ind[index] = 1; a[j] = *(arr + index); } for (int j = 0; j < n; j++) { cout << a[j] << " "; } } int main(int argc, char **argv) { cout << "Enter the array size: "; int n; cin >> n; cout << "Enter the array elements: "; int a[n]; for (int j = 0; j < n; j++) { cin >> a[j]; } fisherYatesShuffling(a, n); } ```