我可以使用Sort或OrderBy对列表进行排序.哪一个更快?两者都在使用相同的算法吗?
List<Person> persons = new List<Person>();
persons.Add(new Person("P005", "Janson"));
persons.Add(new Person("P002", "Aravind"));
persons.Add(new Person("P007", "Kazhal"));
Run Code Online (Sandbox Code Playgroud)
1.
persons.Sort((p1,p2)=>string.Compare(p1.Name,p2.Name,true));
Run Code Online (Sandbox Code Playgroud)
2.
var query = persons.OrderBy(n => n.Name, new NameComparer());
class NameComparer : IComparer<string>
{
public int Compare(string x,string y)
{
return string.Compare(x, y, true);
}
}
Run Code Online (Sandbox Code Playgroud) .NET Array.Sort()方法使用的排序算法是一种稳定的算法吗?
.NET的Array.Sort()方法使用哪种排序算法?
当我们IComparer在课堂上实现时,有没有人知道.net使用了哪种排序算法?
这个帖子说LINQ OrderBy使用Quicksort.我正在努力解决这个问题,因为它OrderBy返回了一个IEnumerable.
我们以下面的代码为例.
int[] arr = new int[] { 1, -1, 0, 60, -1032, 9, 1 };
var ordered = arr.OrderBy(i => i);
foreach(int i in ordered)
Console.WriteLine(i);
Run Code Online (Sandbox Code Playgroud)
循环相当于
var mover = ordered.GetEnumerator();
while(mover.MoveNext())
Console.WriteLine(mover.Current);
Run Code Online (Sandbox Code Playgroud)
在MoveNext()返回下一个最小元素.该LINQ工作,除非你通过使用查询的"套现"的方式ToList()或类似的,还有不应该产生的任何中间的列表,所以每次你打电话MoveNext()的IEnumerator找到下一个最小元素.这没有意义,因为在Quicksort的执行过程中,没有当前最小和下一个最小元素的概念.
我在这里思考的缺陷在哪里?
我发现当我为我的一个类实现CompareTo(..)时,机器之间的排序是不一致的.当两个对象相等时,它们并不总是以相同的顺序排序.我假设一些单线程迭代方法将用于排序,所以我会假设一致的排序.
鉴于以下课程..
class Property : ICompareable<Property>
{
public int Value;
public int Name;
public int CompareTo(Property other)
{
if(this.Value > other.Value)
return 1;
if(this.Value < other.Value)
return -1;
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
并给出以下对象
{
List.add(new Property( name="apple", value = 1) );
List.add(new Property( name="grape", value = 2) );
List.add(new Property( name="banana", value = 1) );
}
Run Code Online (Sandbox Code Playgroud)
当我执行
List.sort();
Run Code Online (Sandbox Code Playgroud)
然后当使用索引单步执行列表时,banana和apple的顺序会根据我正在执行代码的PC而改变.为什么是这样?