
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++
Shuffling an array means rearranging its elements in a random order. The Fisher-Yates algorithm creates a shuffle where every possible order is equally likely to happen. In this article, we'll show you how to write a C++ program that uses Fisher-Yates algorithm to shuffle an array.
Fisher-Yates Algorithm to Shuffle an Array
To shuffle an array, we use the Fisher-Yates algorithm. It works by swapping each element with another randomly selected element from the part of the array that we haven't shuffled yet.
Here are the steps we follow:
- First, we start with the last element of the array.
- Second, we pick a random index from the start of the array up to the current element's position.
- Next, we swap the current element with the element at the random index.
- Then, we move one step backward and repeat the process.
- Finally, we continue until we reach the first element, completing the shuffle.
C++ Program to Shuffle an Array Using Fisher-Yates Algorithm
Below is a C++ program where we use the Fisher-Yates algorithm to shuffle the elements of an array in random order. This method is fair because each item has an equal chance to appear in any position.
#include#include #include using namespace std; // Function to perform Fisher-Yates shuffle on array arr of size n void fisherYatesShuffle(int arr[], int n) { srand(time(0)); // Start from the last element and swap with a random element before it (including itself) for (int i = n - 1; i > 0; i--) { // Generate a random index between 0 and i int j = rand() % (i + 1); // Swap arr[i] with arr[j] int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Original array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } cout << endl; // Shuffle the array fisherYatesShuffle(arr, n); cout << "Shuffled array: "; for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0; }
The output below shows the original array and the shuffled array using the Fisher-Yates algorithm.
Original array: 1 2 3 4 5 6 7 8 9 Shuffled array: 3 4 6 7 8 1 9 2 5