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

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

    A good linear-time shuffling algorithm is the Fisher-Yates shuffle.

    One problem you'll find with your proposed algorithm is that as you near the end of the shuffle, your loop will spend a lot of time looking for randomly chosen elements that have not yet been swapped. This may take an indeterminate amount of time once it gets to the last element to swap.

    Also, it looks like your algorithm will never terminate if there are an odd number of elements to sort.

提交回复
热议问题