我想使用IComparable
& IComparer
进行灵活排序,我将排序方法作为参数 Object[]
& IComparer
。而且我只能放链接类型,怎么放原始类型的数组?
private void QuickSort(Object[] comparables, int low, int high)
{
if (comparables.Length == 0)
{
return;
}
if (low >= high)
{
return;
}
int middle = low + (high - low) / 2;
Object backbone = comparables[middle];
int i = low;
int j = high;
while (i <= j)
{
//while (comparables[i].CompareTo(backbone) < 0)
while (_comparator.Compare(comparables[i], backbone) < 0)
{
i++;
}
//while (comparables[j].CompareTo(backbone) > 0)
while (_comparator.Compare(comparables[j], backbone) > 0)
{
j--;
}
if (i <= j)
{
Object temp = comparables[i];
comparables[i] = comparables[j];
comparables[j] = temp;
i++;
j--;
}
}
if (low < j)
{
QuickSort(comparables, low, j);
}
if (high > i)
{
QuickSort(comparables, i, high);
}
}
public void QuickSort(Object[] comparables, SortOrders order)
{
_comparator = SortFactory.Instance.GetComparer(order);
QuickSort(comparables, 0, comparables.Length - 1);
}
最佳答案
使用C# generics参数化和限制函数参数类型。
实现示例:
public static void QuickSort<T>(T[] a, int from, int to, IComparer<T> comparer)
{
...
if (comparer.Compare(a[i], pivot) < 0)
public static void QuickSort<T>(T[] a, int from, int to) where T : IComparable<T>
{
...
if (a[i].CompareTo(pivot) < 0)
更多信息请查看:
- What is cool about generics, why use them?关于 StackOverflow 的讨论
- Array.Sort Method (T[], Int32, Int32, IComparer) MSDN 上的页面
关于c# - 如何进行灵活排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898553/