and to shuffle lists? Random
OrderBy
This article explores the efficiency of using the and
Random
Code working principle OrderBy
var r = new Random(); var shuffled = ordered.OrderBy(x => r.Next());
class to generate random numbers. For each element in the list, the method uses Lambda expression to allocate a random number for it. Then, the list is sorted according to these random numbers to achieve shuffling effects.
What is the efficiency of this shuffle algorithm? Random
ordered
Although this code can achieve the purpose of shuffling, its efficiency is problematic. OrderBy
The bottom layer of the method uses O (N Log N) sorting algorithm, which is too complicated for the reshuffle task, because the reshuffle only requires the time complexity of O (n). x => r.Next()
The more effective shuffle algorithm is the Fisher-Yates shuffle algorithm. It is easy to understand and has time complexity of O (N). For convenience and clarity, you can create a
expansion method using the Fisher-Yates algorithm.
OrderBy
Fisher-Yates shuffle algorithm through iteration lists, exchanging elements with random selected elements to achieve shuffling. The following is a simple expansion method (unlimited check):
Using the Fisher-Yates algorithm can avoid the calculation overhead brought by while maintaining the shuffling function.
The above is the detailed content of Is Using `OrderBy` with `Random` an Efficient Way to Shuffle a List?. For more information, please follow other related articles on the PHP Chinese website!