C# 在C语言中,用括号中的两个参数调用Sort意味着什么?
我最近在网上遇到了Djikstra最短路径算法的一个实现,并发现了以下调用。 给定一个int类型的节点列表和一个distance类型的字典,下面的调用是什么意思C# 在C语言中,用括号中的两个参数调用Sort意味着什么?,c#,.net,performance,linq,sorting,C#,.net,Performance,Linq,Sorting,我最近在网上遇到了Djikstra最短路径算法的一个实现,并发现了以下调用。 给定一个int类型的节点列表和一个distance类型的字典,下面的调用是什么意思 nodes.Sort((x, y) => distances[x] - distances[y]); 完整代码如下: public List<int> shortest_path(int start, int finish) { var previous = new Dictionary<int, in
nodes.Sort((x, y) => distances[x] - distances[y]);
完整代码如下:
public List<int> shortest_path(int start, int finish)
{
var previous = new Dictionary<int, int>();
var distances = new Dictionary<int, int>();
var nodes = new List<int>();
List<int> path = null;
foreach (var vertex in vertices)
{
if (vertex.Item1 == start)
{
distances[vertex.Item1] = 0;
}
else
{
distances[vertex.Item1] = int.MaxValue / 2;
}
nodes.Add(vertex.Item1);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<int>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest].Item2)
{
var alt = distances[smallest] + neighbor.Item2;
if (alt < distances[neighbor.Item1])
{
distances[neighbor.Item1] = alt;
previous[neighbor.Item1] = smallest;
}
}
}
return path;
}
我寻找了很多答案,但似乎没有任何明确的解释它的意思。
我知道,在LINQ中,通常调用Array.Selectx,I=>。。。意味着x是数组中的实际元素,i是数组中元素x的索引,但上面的情况似乎不是这样
感谢您的解释。排序是通过一次比较两个项目来实现的
括号中的两个参数是回调函数应该比较的两项。List.Sort方法将可选的比较委托作为比较器 在您的示例中:
(x, y) => distances[x] - distances[y]) is a delegate that Sort uses as a comparer.
if distances[x] - distances[y] < 0; x is bigger;
if distances[x] - distances[y] > 0; y is bigger;
if distances[x] - distances[y] > 0; both are even;
此方法将使用指定的System.Comparison对整个列表中的元素进行排序。 其中System.Comparison是一个委托
public delegate int Comparison<in T>(
T x,
T y
)
这样想,您将通过sort方法来决定数组中的哪个元素是另一个元素的先例。排序函数将使用您指定的比较函数来确定返回的排序列表中每个元素的优先级。因此,该函数将获得两个元素,并返回一个值,该值指示前向的结果
设x为第一个参数,y为第二个参数
x < y -> the function will return a number less than 0
x = y -> the function will return 0
x > y -> the function will return a number bigger than 0
总之,传递给Sort方法的这个函数将帮助Sort函数按照您希望的方式对数组进行排序
在C语言中,用括号中的两个参数调用Sort意味着什么
您有以下代码行:
nodes.Sort((x, y) => distances[x] - distances[y]);
您并没有向sort方法传递两个参数,而是传递一个参数,该参数是一个接受两个参数的委托。您基本上在执行以下操作,但使用lambda表示法:
var nodes = new List<int>();
nodes.Sort(SortIt);
请记住,如果使用上述方法执行此操作,则距离必须是类级字段,以便SortIt方法可以访问它。对于lambda表达式,这就是您所拥有的,它将只捕获距离变量,这称为闭包。如果您想知道闭包是什么,请阅读文章。这不是关键。您可以查阅列表的文档。排序,然后挖掘和阅读,直到您了解该函数的第一个参数是什么类型。谢谢,非常有意义。谢谢,我认为你的解释解决了我在这个问题上的基本知识差距。我很高兴我能提供帮助。如果我的回答回答了你的问题,那么请阅读
private int SortIt(int x, int y)
{
return distances[x] - distances[y];
}