Best sorting algorithms for C# / .NET in different scenarios


Question

What are the best algorithms for sorting data in C#?

Is there one sorting algorithm that can handle 80% of sorts well?

Please give code examples if applicable.

1
33
11/4/2008 4:47:25 PM

Accepted Answer

Check out this site: Sorting Comparisons with Animations

Short answer: Quick Sort

Longer answer: The above site will show you the strengths and weaknesses of each algorithm with some nifty animations.

The short answer is there is no best all around sort (but you knew that since you said 80% of the time :) ) but Quick Sort (or 3 Way Quick Sort) will probably be the best general algorithm you could use.

It is the algorithm used by default for Lists in .Net, so you can just call .Sort if what you have is already in a list.

There is pseudo-code on the website I pointed you to above if you want to see how to implement this.

43
2/21/2019 6:27:40 PM

What are you trying to sort? Is there any reason not to use:

List<T>.Sort() ? 

I'm sure this uses QuickSort and you don't have to worry about making any coding errors. You can implement IComparable to change what you want to sort on.

If all your data doesn't fit in memory... well the you're off to the races with Merge sort or something along those lines.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon