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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s