ExtensionMethod.NET Home of 818 C#, Visual Basic, F# and Javascript extension methods

Shuffle

Shuffle an array in O(n) time (fastest possible way in theory and practice!)

Source

public static T[] Shuffle<T>(this T[] list)
{
    var r = new Random((int)DateTime.Now.Ticks);
    for (int i = list.Length - 1; i > 0; i--)
    {
        int j = r.Next(0, i - 1);
        var e = list[i];
        list[i] = list[j];
        list[j] = e;
    }
    return list;
}

Example

int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
a.Shuffle();

Author: Maarten van Duren

Submitted on: 20 mrt 2013

Language: C#

Type: System.Array

Views: 3411