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

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

Mary-Kate Olsen
Release: 2025-01-31 18:51:10
Original
957 people have browsed it

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

What is the efficiency of using

and to shuffle lists? Random OrderBy This article explores the efficiency of using the and

method to shuffle lists. Code examples are as follows:

Random Code working principle OrderBy

var r = new Random();
var shuffled = ordered.OrderBy(x => r.Next());
Copy after login
This code uses

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()

Better and considering factors

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template