Sorting a List with type T

I'm trying to sort a list of type <T> with bubble sort. Unfortunately I have issues with comparing objects with unknown type.

What I've tried so far:

public static void BubbleSort<T>(this List<T> array)
{
    for (int i = (array.Count - 1); i >= 0; i--)
    {
        for (int j = 1; j <= i; j++)
        {
            if (array[j - 1] > array[j]) // issue here
            {
                var temp = array[j - 1];
                array[j - 1] = array[j];
                array[j] = temp;
            }
        }
    }
}
Jon Skeet
people
quotationmark

If you don't need to have anything other than the default comparison, you can use:

// TODO: Rename the parameter...
public static void BubbleSort<T>(this List<T> array)
{
    IComparer<T> comparer = Comparer<T>.Default;
    ...
    if (comparer.Compare(array[j - 1], array[j]) > 0)
    {
        ...
    }
}

Or to allow custom comparisons:

public static void BubbleSort<T>(this List<T> array, IComparer<T> comparer)
{
    ...
    if (comparer.Compare(array[j - 1], array[j]) > 0)
    {
        ...
    }
}

Or to restrict T to types which implement IComparable<T>:

public static void BubbleSort<T>(this List<T> array) where T : IComparable<T>
{
    ...
    if (array[j - 1].CompareTo(array[j]) > 0)
    {
        ...
    }
}

Note that adding the constraint on T here means that any caller needs to know that the type argument they use needs to implement IComparable<T>... it makes it safer at compile-time, at the cost of the constraint being propagated up the call chain. (One option would be to allow a constrained version without a comparer and an unconstrained version with a comparer.)

people

See more on this question at Stackoverflow