creating a generic sort method

后端 未结 2 1456
后悔当初
后悔当初 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:40

    First step is to actually use generics:

    void QuickSort<T>(T[] array, ...)
    

    and

    int Partition<T>(T[] array, ...)
    

    In Partition remove the generic argument from Swap. It will be inferred by the compiler.

    However, for this to work, you need to constrain T to IComparable<T>:

    void QuickSort<T>(T[] array, ...) where T : IComparable<T>
    

    and

    int Partition<T>(T[] array, ...) where T : IComparable<T>
    

    Finally, you need to replace the "less than" and "greater than" operators with calls to CompareTo:

    if(array[midPoint].CompareTo(array[lowerBound]) < 0)
    

    and

    if(array[midPoint].CompareTo(array[lowerBound]) > 0)
    
    0 讨论(0)
  • 2020-12-12 04:53

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

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

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

    It might also be helpful to link you to the MSDN article for IComparable<T>. 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<int>(..., the compiler can infer the type as int and you can simply call it as Swap(....

    0 讨论(0)
提交回复
热议问题