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

前端 未结 12 1386
长发绾君心
长发绾君心 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 13:05

    I am not sure of the efficiency factor, but I have used something similar to the following, if you aren't opposed to using an ArrayList:

    private ArrayList ShuffleArrayList(ArrayList source)
    {
        ArrayList sortedList = new ArrayList();
        Random generator = new Random();
    
        while (source.Count > 0)
        {
            int position = generator.Next(source.Count);
            sortedList.Add(source[position]);
            source.RemoveAt(position);
        }
    
        return sortedList;
    }
    

    Using this, you do not have to worry about the intermediate swapping.

提交回复
热议问题