Dan Esparza
Dan Esparza

Reputation: 28375

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

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.

Upvotes: 37

Views: 50384

Answers (4)

CubanX
CubanX

Reputation: 5252

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.

Upvotes: 51

Yadira Garnica
Yadira Garnica

Reputation: 59

The Bubblesort and the Insertionsort are O(n^2), the Mergesort and the Quicksort are O(nlogn). You can use Sort() method from List, that implements Quicksort, or also you can try implement it and adapt it to yours needs. Here is a basic implementation: Quicksort

//O(nlogn) 
public static void QuickSort(int[] array, int init, int end)
{
   if (init < end)
   {
       int pivot = Partition(array, init, end);
       QuickSort(array, init, pivot-1);
       QuickSort(array, pivot + 1, end);
   }   
}

//O(n)
private static int Partition(int[] array, int init, int end)
{
   int last = array[end];
   int i = init - 1;
   for (int j = init; j < end; j++)
   {
        if (array[j] <= last)
        {
            i++;
            Exchange(array, i, j);     
         }
    }
    Exchange(array, i + 1, end);
    return i + 1;
}

private static void Exchange(int[] array, int i, int j)
{
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

From http://yadiragarnicabonome.com/sorting-arrays/

Upvotes: 2

Keltex
Keltex

Reputation: 26426

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.

Upvotes: 10

Manu
Manu

Reputation: 29143

try quicksort: http://www.codeproject.com/KB/recipes/QuickSort_gen.aspx

Upvotes: 0

Related Questions