Created
August 20, 2014 18:27
-
-
Save richardkundl/53b3e7c766e1f3481ef7 to your computer and use it in GitHub Desktop.
Fisher-Yates algorithm shuffle an array with O(n) time complexity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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