Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - creating a generic sort method

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 Partition method generic and i have no idea how to do it, any guidance would be appreciated.

public static void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }

    public static int Partition(int[] array, int mid)
    {
        int midPoint = mid,
            upperBound = array.Length - 1,
            lowerBound = 0;
        while (lowerBound != upperBound)
        {
            while (midPoint < upperBound)
            {
                if (array[midPoint] > array[upperBound])
                {
                    Swap<int>(ref array[midPoint], ref array[upperBound]);
                    midPoint = upperBound;
                    break;
                }
                upperBound--;
            }
            while (midPoint > lowerBound)
            {
                if (array[midPoint] < array[lowerBound])
                {
                    Swap<int>(ref array[midPoint], ref array[lowerBound]);
                    midPoint = lowerBound;
                    break;
                }
                lowerBound++;
            }
        }
        return midPoint;
    }

    public static void QuickSort(int[] array,int lower,int upper)
    {
        int mid = Partition(array, (lower + upper) / 2);

        if (upper <= lower)
        {
        }
        else
        {
            QuickSort(array, mid + 1, upper);
            QuickSort(array, lower, mid - 1);
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...