使用嵌套的 For 循环对数字元组列表进行排序。 .Net 4.0 C#

Sort a List of numeric Tuples with nested For Loops. .Net 4.0 C#

我有一个数字元组列表,想用嵌套的 For 循环按 Item1 对它进行排序。我知道我可以做 List.Sort();但我也想用 For 循环来做,这样我就可以比较性能。感谢您的帮助。

        List<Tuple<double, int, int>> FHM = new List<Tuple<double, int, int>>(); 
        FHM.Add(Tuple.Create(2500.00, 1, 5));
        FHM.Add(Tuple.Create(2400.00, 2, 300));    
        FHM.Add(Tuple.Create(2300.00, 4, 10));
        FHM.Add(Tuple.Create(2600.00, 1, 325));

我试图实现下面的代码,可以很好地对带有嵌套 for 循环的双精度列表进行排序,但我无法为元组重新编码...

List<double> FH = new List<double>() { 2510, 2509, 2501.5, 2501.75 };


        var S1 = Stopwatch.StartNew();
        double temp;
        for (int i = 0; i < FH.Count; i++)
        {
            for (int n = 0; n < i; n++)
            {
                if (FH[n] > FH[i])
                {
                    temp = FH[i];
                    FH[i] = FH[n];
                    FH[n] = temp;
                }
            }
        }
        S1.Stop();
        Console.WriteLine($"S1 Ticks = " + S1.ElapsedTicks);

/* ForLoop 的 ElapsedTicks 是 4000。而 FH.Sort();是 16000。所以我希望带有元组的 ForLoop 版本对于我正在处理的短列表表现更好。 */

由于您似乎不关心排序算法本身,您可以遍历元组并将排序卸载到 SortedList,如下所示:

Sort a List of numeric Tuples

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            List<Tuple<double, int, int>> FHM = new List<Tuple<double, int, int>>();
            FHM.Add(Tuple.Create(2500.00, 1, 5));
            FHM.Add(Tuple.Create(2400.00, 2, 300));
            FHM.Add(Tuple.Create(2300.00, 4, 10));
            FHM.Add(Tuple.Create(2600.00, 1, 325));

            var sorted = new SortedList<double, Tuple<double, int, int>>();
            foreach (Tuple<double, int, int> t in FHM)
            {
                sorted.Add(t.Item1, t);
            }
        }
    }
}
        var S2 = Stopwatch.StartNew();

        var temp = Tuple.Create(0.00, 0, 0);

        for (int i = 0; i < FHM.Count; i++)
        {
            for (int n = 0; n < i; n++)
            {
                if (FHM[n].Item1 > FHM[i].Item1)
                {
                    temp = FHM[i];
                    FHM[i] = FHM[n];
                    FHM[n] = temp;
                }
            }
        }

        S2.Stop();
        Console.WriteLine("Ticks S2 ForLoop = " + S2.ElapsedTicks); // 4000 ElapsedTicks

        S2.Reset();
        S2.Start();

        FHM.Sort();

        S2.Stop();
        Console.WriteLine("Ticks S2 List.Sort(); = " + S2.ElapsedTicks); // 700000 ElapsedTicks