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

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

    static Random random = new Random();
    
    public static IEnumerable RandomPermutation(IEnumerable sequence)
    {
        T[] retArray = sequence.ToArray();
    
    
        for (int i = 0; i < retArray.Length - 1; i += 1)
        {
            int swapIndex = random.Next(i, retArray.Length);
            if (swapIndex != i) {
                T temp = retArray[i];
                retArray[i] = retArray[swapIndex];
                retArray[swapIndex] = temp;
            }
        }
    
        return retArray;
    }
    

    modified to handle lists or other objects implementing IEnumerable

提交回复
热议问题