Efficient random sorting algorithm for C# integer list
This article explores a more efficient way to randomly sort or shuffle a list of integers.
Fisher-Yates Shuffling Algorithm
The Fisher-Yates shuffling algorithm is a linear-time algorithm that efficiently randomizes lists. Here’s how it works:
For each index i in the list from 0 to n-1, do the following:
<code>int j = random.Next(i + 1); 交换索引i和j处的数值;</code>
Improve existing problems in the algorithm
The proposed algorithm has some shortcomings:
Code implementation
The following code snippet implements the Fisher-Yates shuffling algorithm in C#:
using System; using System.Collections.Generic; class Program { static void Shuffle<T>(IList<T> list) { Random random = new Random(); for (int i = 0; i < list.Count; i++) { int j = random.Next(i + 1); T temp = list[i]; list[i] = list[j]; list[j] = temp; } } static void Main(string[] args) { List<int> values = new List<int>(); for (int i = 0; i < 10; i++) { values.Add(i); } Shuffle(values); Console.WriteLine(string.Join(", ", values)); } }
The above is the detailed content of How Can We Efficiently Shuffle an Integer List in C#?. For more information, please follow other related articles on the PHP Chinese website!