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!