Home > Backend Development > C++ > How Can We Efficiently Shuffle an Integer List in C#?

How Can We Efficiently Shuffle an Integer List in C#?

DDD
Release: 2025-01-21 14:02:14
Original
952 people have browsed it

How Can We Efficiently Shuffle an Integer List in C#?

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>
Copy after login

Improve existing problems in the algorithm

The proposed algorithm has some shortcomings:

  • Inefficiency at the end: As the algorithm progresses, it becomes increasingly difficult to find unswapped elements, leading to inefficiency.
  • Infinite loop: When the number of elements is an odd number, the algorithm will not terminate because it cannot find a suitable exchange candidate.

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));
    }
}
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template