37

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
  • If a stable algorithm is required in particular, LINQ's order methods (e.g. OrderBy) use a stable quicksort that seems intended to be suitable for most scenarios. Commented Jul 10, 2020 at 15:18

5 Answers 5

51

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Note that C#'s List<T>.Sort` implementation is quite clever. It is a quicksort that detects the degenerate case, falling back to heapsort if things get out of hand. This way, it mitigates one of quicksort's greatest shortcomings. I'm assuming it also cuts off to insertion sort whenever a partition is below a certain size (a very common optimization), although I don't remember for sure. It is, however, unstable.
10

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.

Comments

2

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/

1 Comment

Quicksort is Big O(n²) as Big O is worst case scenario you gave its average scenario which is Big Theta aka Θ(n log(n)). Quicksort is one of the worse for Big O for time complexity. Mergesort, Heapsort, or Cubesort (or variations) are common sort alogrithms with Big O(n log(n)) time complexity. You typically have to get into something more specialized or complex to do better in Big O. If you can use it a Heapsort is the best well-balanced algorithm across in my opinion for Time (Big Omega, Theta, and O) and Space (Big O).
0

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

Comments

0

I have created two different algorithms, looks like more logical.

 public static T[] SortT<T>(T[] a) where T:IComparable<T>
 {
     T[] result = new T[a.Length];

     int current = 0;
     for (int i = 0; i < a.Length; i++)
     {
         current = 0;
         for (int j = 0; j < a.Length; j++)
         {
             if (a[i].CompareTo(a[j])>0)
                 current++;
         }
         result[current] = a[i];
     }

     for (int i = 1; i < result.Length; i++)
         if (result[i].CompareTo(default(T))==0)
             result[i] = result[i - 1];

     return result;
 }


 // for sorting big data class w/out creating new Tarray.
 public static void SortSwapT<T>(ref T[] a) where T:IComparable<T>
 {
     int[] indCurrent = new int[a.Length];
     Dictionary<int, int> currentInd = new Dictionary<int, int>();

     int current;
     for (int i = 0; i < a.Length; i++)
     {
         current = 0;
         for (int j = 0; j < a.Length; j++)
         {
             if (a[i].CompareTo(a[j])>0)
                 current++;
         }
         indCurrent[i] = current;
     }

     for (int i = 0; i < indCurrent.Length; i++)
     {
         while (currentInd.ContainsKey(indCurrent[i]))
             indCurrent[i] += 1;
         currentInd.Add(indCurrent[i], i);
     }

     T temp;
     for (int i = 0; i < a.Length - 1; i++)
     {
         temp = a[i];
         a[i] = a[currentInd[i]];
         a[currentInd[i]] = temp;

         currentInd[indCurrent[i]] = currentInd[i];
         indCurrent[currentInd[i]] = indCurrent[i];
     }
 }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.