Fisher-Yates Shuffle algorithm
Fisher-Yates Shuffle algorithm
Description:
An algorithm for shuffling a finite sequence into randomized permutation.
Process:
Let arr be a finite sequence. Let n be the length of the finite sequence arr.
for i from n-1 downto 1 do:
j<- a random number which 0<=j<=i;
swap arr[i],arr[j];
Time Complexity:
O(n) where n is length of the sequence
Code(C#):
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
char[] c = { 'A', 'B', 'C', 'D', 'E' };
Console.Write("Before:");
PrintSequence(c);
Console.WriteLine();
FisherYatesShuffleFunc(ref c);
Console.Write("After:");
PrintSequence(c);
Console.WriteLine();
}
static void FisherYatesShuffleFunc(ref char[] s)
{
Random r = new Random();
for(int i=s.Length-1;i>=1;i--)
{
int j = r.Next(i + 1);
char t=s[i];
s[i] = s[j];
s[j] = t;
}
}
static void PrintSequence(char []s)
{
Console.Write(s);
}
}
e.g.
Input: arr=['A','B','C','D','E'] , n=5
(1)i=4. Let j=3;
swap arr[4] and arr[3]
result:arr=['A','B','C','E','D']
(2)i=3. Let j=1;
swap arr[3] and arr[1]
result:arr=['A','E','C','B','D']
(3)i=2. Let j=1;
swap arr[2] and arr[1]
result:arr=['A','C','E','B','D']
(4)i=1. Let j=0;
swap arr[1] and arr[0]
result:arr=['C,'A','E','B','D']
Done: output:arr=['C,'A','E','B','D']
Comments
Post a Comment