Shuffle algorithm is very useful in many programs. The algorightm can reorder the elements in a set randomly. It is used in the field of network, data processing, etc.
The algorithm is very simple. We have N elements in the Array and we want to rerange the elements again in a random order.
The code is as follows:
#include <time.h> #include <stdio.h> #include <iostream> #include <algorithm> template<typename T> void output(T * array,int n) { for(int i = 0 ;i < n;++i) { std::cout<<"array["<<i<<"] = "<<array[i]<<","; } std::cout<<std::endl; } template<typename T> void swap(T & a ,T & b) { T c = a; a = b; b = c; } template<typename T> void randomize(T * tarray ,int n) { T * array = new T[n]; std::copy(tarray,tarray+n,array); int i = n - 1; for(i;i>=0;--i) { swap(array[i],array[(rand()%(i+1))]); } output(array,n); delete []array; } int main() { srand(time(NULL)); int array[]={1,2,3,4,5,6,7,8,9,0}; for(int i = 0 ; i < 10;i++) { randomize(array,10); } return 0; }
The algorithm procedure is like this:
Use a pointer j to point to the end of the array and traverse the array from the end.
Randomly choose a element in the array from begining to the pointer j and swap element pointer j points to and element selected randomly just now. then pointer j move one step to left. the algorithm can make sure that all the element can have the same probability to be put in every unit in the array, which means it can generate a fully random element order.