c# - 如何进行灵活排序

标签 c# algorithm sorting computer-science quicksort

我想使用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)

更多信息请查看:

关于c# - 如何进行灵活排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898553/

相关文章:

c# - 如何在 iOS mono 中禁用后退按钮

c# - 我应该等待使用 TaskCompletionSource 的同步 Task<T> 吗?

algorithm - 计算问答游戏的准确性

Python 奇怪的返回问题

c# - 改变我的命名空间是一件好事还是必要的?

algorithm - 如何将威胁空间搜索添加到我的井字游戏算法中?

c++ - 桶排序实现

java - JSP 显示标签排序页面重新加载

java - 使用键升序排序arraylist

c# - 有什么方法可以使此查询更快并在循环外构建 where 子句吗?