Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
How to Reverse an Array using STL in C++?
Next article icon

Shuffle an Array using STL in C++

Last Updated : 27 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array, the task is to shuffle the whole array and print it.
Example 
 

Input  (1, 2, 3, 4, 5, 6, 7} Output  {3, 1, 6, 7, 2, 4, 5}  Input  (1, 2, 3} Output  {3, 1, 2}


 


STL contains two methods which can be used to get a shuffled array. These are namely shuffle() and random_shuffle().
 

shuffle


This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator. It swaps the value of each element with that of some other randomly picked element. It determines the element picked by calling g().
Template 
 

template    void shuffle (RandomAccessIterator first,                  RandomAccessIterator last,                  URNG&& g) {   for (auto i=(last-first)-1; i>0; --i) {     std::uniform_int_distribution d(0, i);     swap (first[i], first[d(g)]);   } }


Implementation
 

CPP
// C++ program to shuffle // the given array // using shuffle() method  #include <bits/stdc++.h> using namespace std;  // Shuffle array void shuffle_array(int arr[], int n) {      // To obtain a time-based seed     unsigned seed = 0;      // Shuffling our array     shuffle(arr, arr + n,             default_random_engine(seed));      // Printing our array     for (int i = 0; i < n; ++i)         cout << arr[i] << " ";     cout << endl; }  // Driver code int main() {      int a[] = { 10, 20, 30, 40 };      int n = sizeof(a) / sizeof(a[0]);      shuffle_array(a, n);      return 0; } 

Output: 
30 10 20 40

 

Note: Output may differ each time because of the random function used in the program.
 

random_shuffle


This function randomly rearranges elements in the range [first, last). It swaps the value of each element with some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness.
Template 
 

template    void random_shuffle (RandomAccessIterator first,                         RandomAccessIterator last,                        RandomNumberGenerator& gen) {   iterator_traits::difference_type i, n;   n = (last-first);   for (i=n-1; i>0; --i) {     swap (first[i], first[gen(i+1)]);   } }


Implementation
 

CPP14
// C++ program to shuffle // the given array // using random_shuffle() method  #include <bits/stdc++.h> using namespace std;  // Shuffle array void shuffle_array(int arr[], int n) {      // To obtain a time-based seed     unsigned seed = 0;      // Shuffling our array using random_shuffle     random_shuffle(arr, arr + n);      // Printing our array     for (int i = 0; i < n; ++i)         cout << arr[i] << " ";     cout << endl; }  // Driver code int main() {      int a[] = { 10, 20, 30, 40 };      int n = sizeof(a) / sizeof(a[0]);      shuffle_array(a, n);      return 0; } 

Output: 
10 40 20 30

 

Note: Output may differ each time because of the random function used in the program.
 

Which is better?


 

  • shuffle introduced after C11++, uses functions which are better than rand() which random_shuffle uses.
  • shuffle is an improvement over random_shuffle, and we should prefer using the former for better results.
  • If we don't pass our random generating function in random_shuffle then it uses its unspecified random values due to which all successive values are correlated.


 


Next Article
How to Reverse an Array using STL in C++?

S

ShivamChauhan5
Improve
Article Tags :
  • C++ Programs
  • C++
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • How to Reverse an Array using STL in C++?
    Reversing an array means rearranging its elements so that the first element becomes the last, the second element becomes the second last, and so on. In this article, we will learn how to reverse an array using STL in C++. The most efficient way to reverse an array using STL is by using reverse() fun
    3 min read
  • Find All Permutations of an Array using STL in C++
    The permutation of an array refers to a rearrangement of its elements in every possible order. In this article, we will learn how to generate all possible permutation of an array using STL in C++. The simplest method to find all the permutations of an array is to use next_permutation(). The array ha
    2 min read
  • How to Resize an Array of Strings in C++?
    In C++, the array of strings is useful for storing many strings in the same container. Sometimes, we need to change the size of this array. In this article, we will look at how to resize the array of strings in C++. Resize String Array in C++There is no way to directly resize the previously allocate
    2 min read
  • All reverse permutations of an array using STL in C++
    Given an array, the task is to print or display all the reverse permutations of this array using STL in C++. Reverse permutation means, for an array {1, 2, 3}: forward permutations: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 reverse permutations: 3 2 1 3 1 2 2 3 1 2 1 3 1 3 2 1 2 3 Examples: Input: a[] = {
    3 min read
  • Working with Array and Vectors using STL in C++
    Using STL library it is very easy to perform certain basic operations on array like Sorting, searching, sum of elements, finding minimum and maximum element of the array. Sorting Sorting can be done with the help of sort() function. sort(starting_index, last_index) – To sort the given array/vector.
    6 min read
  • How to Sort an Array in C++?
    Sorting an array involves rearranging its elements in a specific order such as from smallest to largest element or from largest to smallest element, etc. In this article, we will learn how to sort an array in C++. Example: Input: arr ={5,4,1,2,3}Output: 1 2 3 4 5Explanation: arr is sorted in increas
    4 min read
  • How to Sort an Array of Strings Using Pointers in C++?
    In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done. The task is to sort a given array of strings using pointers. Example
    2 min read
  • How to find the sum of elements of an Array using STL in C++?
    Given an array arr[], find the sum of the elements of this array using STL in C++. Example: Input: arr[] = {1, 45, 54, 71, 76, 12} Output: 259 Input: arr[] = {1, 7, 5, 4, 6, 12} Output: 35 Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax: accumulate(first_ind
    1 min read
  • Sorting Vector of Arrays in C++
    Given a vector of arrays, the task is to sort them. Examples: Input: [[1, 2, 3], [10, 20, 30], [30, 60, 90], [10, 20, 10]] Output: [[1, 2, 3], [10, 20, 10], [10, 20, 30], [30, 60, 90]] Input: [[7, 2, 9], [5, 20, 11], [6, 16, 19]] Output: [[5, 20, 11], [6, 16, 19], [7, 2, 9]] Approach: To sort the Ve
    2 min read
  • How to Sort an Array in Descending Order using STL in C++?
    Sort an array in descending order means arranging the elements in such a way that the largest element at first place, second largest at second place and so on. In this article, we will learn how to sort an array in descending order using STL in C++. Examples Input: arr[] = {11, 9, 45, 21};Output: 78
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences