Home >Backend Development >C++ >How Can the Fisher-Yates Shuffle Achieve Linear-Time Random Shuffling?

How Can the Fisher-Yates Shuffle Achieve Linear-Time Random Shuffling?

Barbara Streisand
Barbara StreisandOriginal
2025-01-21 14:06:11378browse

How Can the Fisher-Yates Shuffle Achieve Linear-Time Random Shuffling?

Fisher-Yates shuffling algorithm: a linear time shuffling algorithm

Efficiency is crucial when randomly sorting a list of integers. Although the original method in the question attempts to achieve randomness, it may encounter efficiency problems during the processing, especially near the end.

A more efficient solution is the Fisher-Yates shuffling algorithm, a linear-time algorithm that ensures truly random reordering of the input list. Unlike the original approach, which relied on a Boolean array to keep track of swapped elements, the Fisher-Yates shuffling algorithm takes a simpler approach.

<code class="language-c#">for (int i = iItemCount - 1; i >= 1; i--)
{
    int j = random.Next(i + 1);
    int temp = values[j];
    values[j] = values[i];
    values[i] = temp;
}</code>

The algorithm works by repeatedly exchanging the current element with a previously randomly selected element in the list. As the algorithm proceeds, it narrows down the range of unsorted elements, effectively shuffling the entire list in O(n) time.

Using the Fisher-Yates shuffling algorithm, you can efficiently and randomly rearrange a list of integers, avoiding the potential pitfalls of the original algorithm.

The above is the detailed content of How Can the Fisher-Yates Shuffle Achieve Linear-Time Random Shuffling?. 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