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

One thought on “Shuffling an array using Fisher–Yates algorithm

  1. Nauru

    Very good written information. It will be supportive to everyone who usess it, as well as me. Keep up the good work – for sure i will check out more posts.

    Reply

Leave a Reply to Nauru Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>