1

I want to make flexible sort using IComparable & IComparer, and I put in sort method as params Object[] & IComparer. And I can only put link types, how put array of primitive types?

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);
}
L_J
  • 2,351
  • 10
  • 23
  • 28
user280179
  • 63
  • 1
  • 9

1 Answers1

0

Use C# generics to parametrize and restrict function arguments types.

Impementation examples:

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)

For more information check:

Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50