Most efficient way to randomly “sort” (Shuffle) a list of integers in C#

前端 未结 12 1382
长发绾君心
长发绾君心 2020-11-22 12:25

I need to randomly \'sort\' a list of integers (0-1999) in the most efficient way possible. Any ideas?

Currently, I am doing something like this:

bo         


        
12条回答
  •  礼貌的吻别
    2020-11-22 12:51

    We can make an extension method out of this to get a Random enumerator for any IList collection

    class Program
    {
        static void Main(string[] args)
        {
            IList l = new List();
            l.Add(7);
            l.Add(11);
            l.Add(13);
            l.Add(17);
    
            foreach (var i in l.AsRandom())
                Console.WriteLine(i);
    
            Console.ReadLine();
        }
    }
    
    
    public static class MyExtensions
    {
        public static IEnumerable AsRandom(this IList list)
        {
            int[] indexes = Enumerable.Range(0, list.Count).ToArray();
            Random generator = new Random();
    
            for (int i = 0; i < list.Count; ++i )
            {
                int position = generator.Next(i, list.Count);
    
                yield return list[indexes[position]];
    
                indexes[position] = indexes[i];
            }
        }
    }   
    

    This uses a reverse Fisher-Yates shuffle on the indexes of the list we want to randomly enumerate through. Its a bit of a size hog (allocating 4*list.Count bytes), but runs in O(n).

提交回复
热议问题