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

前端 未结 12 1397
长发绾君心
长发绾君心 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:48

    ICR's answer is very fast, but the resulting arrays aren't distributed normally. If you want a normal distribution, here's the code:

        public static IEnumerable RandomPermutation(this IEnumerable sequence, int start,int end)
        {
            T[] array = sequence as T[] ?? sequence.ToArray();
    
            var result = new T[array.Length];
    
            for (int i = 0; i < start; i++)
            {
                result[i] = array[i];
            }
            for (int i = end; i < array.Length; i++)
            {
                result[i] = array[i];
            }
    
            var sortArray=new List>(array.Length-start-(array.Length-end));
            lock (random)
            {
                for (int i = start; i < end; i++)
                {
                    sortArray.Add(new KeyValuePair(random.NextDouble(), array[i]));
                }
            }
    
            sortArray.Sort((i,j)=>i.Key.CompareTo(j.Key));
    
            for (int i = start; i < end; i++)
            {
                result[i] = sortArray[i - start].Value;
            }
    
            return result;
        }
    

    Note that in my tests, this algorithm was 6 times slower than the one ICR provided, however this is the only way I could come up with to get a normal result distribution

提交回复
热议问题