我有一个数字元组列表,并希望通过嵌套的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。因此,我希望带有Tuples的ForLoop版本在我正在处理的候选清单中表现更好。 * /
答案 0 :(得分:1)
由于您似乎对排序算法本身并不关心,因此可以遍历元组并将排序卸载到SortedList,如下所示:
排序数字元组列表
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);
}
}
}
}
答案 1 :(得分:0)
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