Home >Backend Development >C++ >Is Using `Random` and `OrderBy` an Efficient Way to Shuffle a List?

Is Using `Random` and `OrderBy` an Efficient Way to Shuffle a List?

Linda Hamilton
Linda HamiltonOriginal
2025-01-31 18:56:10120browse

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

is an effective way to shuffle list.

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:
    Based on random numbering elements may cause deviation shuffling, the frequency of certain elements may be higher than other elements.
  • alternative
  • The better shuffle algorithm is the Fisher-Yates shuffle, which exchanges the element to a random position in the list. This provides a more uniform distribution, and the complexity is O (n).
  • Implement

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn