我正在学习泛型类型并想创建一个泛型 QuickSort 方法,问题是类不是协变的,代码无法编译。问题是使分区方法通用,我不知道该怎么做,任何指导将不胜感激。
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);
}
}