Skip to content

Instantly share code, notes, and snippets.

@richardkundl
Created August 20, 2014 18:27
Show Gist options
  • Save richardkundl/53b3e7c766e1f3481ef7 to your computer and use it in GitHub Desktop.
Save richardkundl/53b3e7c766e1f3481ef7 to your computer and use it in GitHub Desktop.
Fisher-Yates algorithm shuffle an array with O(n) time complexity
/// <summary>
/// Fisher-Yates algorithm with O(n) time complexity
/// </summary>
/// <param name="array">array to be shuffled</param>
/// <returns>shuffled array</returns>
public static int[] FisherYates(int[] array)
{
Random r = new Random();
for (int i = array.Length - 1; i > 0; i--)
{
int index = r.Next(i);
// swap
int tmp = array[index];
array[index] = array[i];
array[i] = tmp;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment