Home >Backend Development >C++ >Is Using `Random` and `OrderBy` an Efficient Way to Shuffle a List?
Use
and shuffle list: Is it an efficient algorithm? Random
OrderBy
This article discusses whether the use of and
Random
Method OrderBy
The code provided to generate a random number for each element, and resume the list based on these numbers:
Evaluation
<code>var r = new Random(); var shuffled = ordered.OrderBy(x => r.Next());</code>Although this method looks very intuitive, it has some shortcomings:
Computing complexity:
The time complexity is O (N Log N), which is inefficient for large lists. The better shuffle algorithm has the complexity of O (N).Potential problems:
This expansion method simplifies the use of Fisher-Yates' shuffle and avoids the needs of generating new arrays.
Conclusion
and can be used for shuffling, but they have the problem of efficiency and deviation. Fisher-Yates shuffle provides a more efficient and non-deviating solution, which is the first choice in most applications that need to be shuffled.
The above is the detailed content of Is Using `Random` and `OrderBy` an Efficient Way to Shuffle a List?. For more information, please follow other related articles on the PHP Chinese website!