Posted By

fixpq on 02/26/12


Tagged

array shuffle Randomize


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

rcraven


Shuffle / randomize array


 / Published in: C#
 

This method shuffles an array. This is the optimum implementation for such an algorithm - O(n).

  1. public static void Shuffle<T>(T[] array)
  2. {
  3. Random random = new Random();
  4.  
  5. for (int i = 0; i < 10; i++)
  6. {
  7. int idx = random.Next(i, 10);
  8.  
  9. //swap elements
  10. T tmp = array[i];
  11. array[i] = array[idx];
  12. array[idx] = tmp;
  13. }
  14. }

Report this snippet  

You need to login to post a comment.