Daily Archives: March 30, 2013

Shuffling an array using Fisher–Yates algorithm

Fisher-Yates is an algorithm to shuffle an array and it was introduced by Richard Durstenfeld in 1964[Source Wikipedia]. It shuffles the elements of the array in place, rather than producing a shuffled copy of the array. This can be an advantage if the array to be shuffled is large.

Code:

namespace MSCoder.ShuffleArray
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] values = { 1, 2, 3, 4, 5 };

            Shuffle<int>(values);

            foreach (var item in values)
            {
                Console.Write(item);
            }

            Console.Read();

        }

        /// <summary>
        /// Shuffles an array
        /// </summary>
        /// <typeparam name="T">Array type</typeparam>
        /// <param name="values">Array</param>
        public static void Shuffle<T>(T[] values)
        {
            Random random = new Random();

            for (int index = values.Length; index > 1; index--)
            {                
                int randValue = random.Next(index);
                
                T temp = values[randValue];
                values[randValue] = values[index - 1];
                values[index - 1] = temp;
            }
        }
    }
}

 

Happy Coding

MSCoder