6

Is there any in-built stable sort routine in .NET?

I know that C++ has an in-built sort routine under "algorithms" std::sort(). Likewise, do we have something to use along with C#?

Also, is there any in-built swap function in .NET?

Joshua
  • 40,822
  • 8
  • 72
  • 132
veda
  • 6,416
  • 15
  • 58
  • 78

1 Answers1

12

Using "C# stable sort" in Google revealed this SO post as top result:

Is the sorting algorithm used by .NET's `Array.Sort()` method a stable algorithm?

So the answer is: Enumerable.OrderBy is a stable sort function, not built into C#, but part of the .NET framework libraries.

Concerning "Swap": I don't know of any prebuilt generic swap function in the .NET framework, but here you find an implementation in less than 10 lines of code:

static void Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}
Community
  • 1
  • 1
Doc Brown
  • 19,739
  • 7
  • 52
  • 88
  • Seems odd that such a commonly used function isn't already in .NET. At least it's easy to implement, I guess. – Nemo Oct 25 '21 at 11:03