Shuffle / randomize array


/ Published in: C#
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.