creating a generic sort method

后端 未结 2 1467
后悔当初
后悔当初 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[] array, ...)
    

    and

    int Partition(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:

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

    and

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

    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)
    

提交回复
热议问题