how was Array.Sort implemented in .NET?

后端 未结 6 557
遇见更好的自我
遇见更好的自我 2021-01-13 21:28

I am using structures in my programming and I sort the structure according to a value in the structure using IComparer.

How did Microsoft implement th

6条回答
  •  旧时难觅i
    2021-01-13 22:32

    Array.Sort(), like most built-in sorters, uses a QuickSort implementation in a helper class behind the scenes. The sort is relatively efficient, and customizable using the IComparable and IComparer interfaces, but it's unstable; the three 1s in your example may end up in a different relative order than they were before the sort. You can see this if you use a more complex structure:

    struct TestStruct
    {
       int a;
       int b;
    }
    
    ...
    
    //As declared, this array is already sorted by both "a" and "b" properties
    var myStructAray = new [] {new TestStruct{a=1,b=1}, new TestStruct{a=1,b=2}, new TestStruct{a=1,b=3});
    
    //QuickSorts myStructArray based on the comparison of the lambda for each element
    var newArray = Array.Sort(myStructArray, x=>x.a); 
    
    //newArray may have a different order as myStructArray at this time
    for(var i=0;i

提交回复
热议问题