C ++ implementation of random shuffling algorithm

Random shuffle algorithm is to make a random set of data.

#include <the iostream> 
#include <Vector> 
#include <the ctime> 
#include <cstdio>
 the using  namespace STD; 

// random shuffling algorithm 
void shuffle (Vector < int > & VEC) 
{ 
    int n-= vec.size ();
     IF (n-<= 0 )
         return ; 
    srand (Time ( 0 )); 

    for ( int i = 0 ; i <n-; i ++ ) 
    { 
        // ensure that each value of bit i is not related to the previous bit i 
        int index = i + rand ()% ( n- I);
        swap(vec[index], vec[i]);
    }
}

int main()
{
    vector<int> vec;
    for(int i = 1; i <= 10; i++)
    {
        vec.push_back(i);
    }
    shuffle(vec);

    for(auto it : vec)
            cout << it << " ";
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/xiaokang01/p/12603618.html