Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Random shuffle in C++

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 758
    Comment on it

    Random shuffle function is used to randomly rearrange the elements in a given range. The random_shuffle function is defined in the STL algorithm.

    Template for random_shuffle

    template <class InputIterator>
      void random_shuffle (InputIterator first, InputIterator last);
    

    About parameters
    InputIterator first
    InputIterator first for the initial position of the range which is included in the range.
    InputIterator last
    InputIterator last for the final position which it not included in the range.


    A sample program using random_shuffle

    #include <iostream>
    #include <algorithm>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
            vector <int> v;
            vector <int>:: iterator it;
    
            // Pushing 11 random elements inside the vector
            v.push_back(1);
            v.push_back(2);
            v.push_back(3);
            v.push_back(4);
            v.push_back(5);
            v.push_back(6);
            v.push_back(7);
            v.push_back(8);
            v.push_back(9);
            v.push_back(10);
            v.push_back(11);
    
            // printing the elemnets inside the range
            cout <<"Elements inside the range." << endl;
            for ( it = v.begin(); it != v.end(); it++)
                    cout << *it << " ";
            cout << endl;
    
            //applying random_shuffle function on the range
            random_shuffle(v.begin(),v.end());
    
            // printing the elemnets inside the range
            cout <<"Elements inside the range after random shuffle." << endl;
            for ( it = v.begin(); it != v.end(); it++)
                    cout << *it << " ";
            cout << endl;
    
            return 0;
    }
    

    Output of the above program

    Elements inside the range.
    1 2 3 4 5 6 7 8 9 10 11 
    Elements inside the range after random shuffle.
    5 11 8 9 1 6 3 2 7 10 4 
    

    Time complexity for random_shuffle is linear in the distance between the range.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: