Mergesort works better on linked lists than it does on arrays. It avoids the need for the auxiliary space, and becomes a simple, reliably O(N log N) sorting algorithm. And as an added bonus, it's stable too.
Here is a quick merge sort algorithm in C#.Net 3.5 (Note - T is my custom node interface) :
For the full implementation of the Custom Doubly Linked List, look at this post.private T Merge_Sort(T first)
{
if (first == null || first.Next == null)
return first;
T second = Split(first);
first = Merge_Sort(first);
second = Merge_Sort(second);
return Merge(first, second);
}
private T Split(T item)
{
if (item == null || item.Next == null)
return null;
T second = item.Next;
item.Next = second.Next;
second.Next = Split(second.Next);
return second;
}
private T Merge(T first,
T second)
{
if (first == null)
return second;
if (second == null)
return first;
// If both are not null, we will run the comparer
// If first is less than second
if (first.CompareTo(second) < 0)
{
first.Next = Merge(first.Next, second);
first.Next.Previous = first;
first.Previous = default(T);
return first;
}
else
{
second.Next = Merge(first, second.Next);
second.Next.Previous = second;
second.Previous = default(T);
return second;
}
}