Shuffles a list in O(n) time by using the Fisher-YatesKnuth algorithm. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Shuffles a list in O(n) time by using the Fisher-YatesKnuth algorithm.

Demo Code


using System.Collections.Generic;
using System.Collections;
using System;/*from   w ww .  j a  v a2 s.  c  o m*/

public class Main{
        /// <summary>
        ///     Shuffles a list in O(n) time by using the Fisher-Yates/Knuth algorithm.
        /// </summary>
        /// <param name="r"></param>
        /// <param name="list"></param>
        public static void Shuffle(this Random r, IList list)
        {
            for (var i = 0; i < list.Count; i++)
            {
                var j = r.Next(0, i + 1);

                var temp = list[j];
                list[j] = list[i];
                list[i] = temp;
            }
        }
}

Related Tutorials