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

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

    As Greg pointed out the Fisher-Yates shuffle would be the best approach. Here is an implementation of the algorithm from Wikipedia:

    public static void shuffle (int[] array)
    {
       Random rng = new Random();   // i.e., java.util.Random.
       int n = array.length;        // The number of items left to shuffle (loop invariant).
       while (n > 1)
       {
          int k = rng.nextInt(n);  // 0 <= k < n.
          n--;                     // n is now the last pertinent index;
          int temp = array[n];     // swap array[n] with array[k] (does nothing if k == n).
          array[n] = array[k];
          array[k] = temp;
       }
    }
    

    The implementation above relies on Random.nextInt(int) providing sufficiently random and unbiased results

提交回复
热议问题