creating a generic sort method

后端 未结 2 1457
后悔当初
后悔当初 2020-12-12 04:34

I am learning generic types and wanted to create a generic QuickSort method, the problem is classes are not co-variant and code cannot compile. the problem is making the Par

2条回答
  •  粉色の甜心
    2020-12-12 04:53

    What you're looking for is to constrain T to any type that implements IComparable

    This MSDN article nicely explains generic constrains in C#. Your method declaration will look like this:

    public static T Partition(T[] array, int mid)
        where T : IComparable
    {
        //code goes here
    }
    
    public static void QuickSort(T[] array, int lower, int upper)
        where T : IComparable
    {
        //code goes here
    }
    

    It might also be helpful to link you to the MSDN article for IComparable. Wherever you'd regularly compare two ints, you would instead call array[midPoint].CompareTo(array[upperBound]) > 0. All the comparison operators are the same if you check the result of CompareTo against 0.

    And a small side note, when you call Swap(..., the compiler can infer the type as int and you can simply call it as Swap(....

提交回复
热议问题