When does Comparer make a Sort throw an ArgumentException?

The documentation for Sort says that Sort will throw an ArgumentException if "the implementation of the comparison failed while sorting. For example, the comparator may not return 0 when comparing the element with itself."

Besides the example given, can someone tell me when this will happen otherwise?

+2
source share
2 answers

The sorting algorithm (QuickSort) is based on the predictable implementation of IComparer. After several tens of layers of indirection in BCL, you find yourself in this method:

public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
    try
    {
        ...
        ArraySortHelper<T>.QuickSort(keys, index, index + (length - 1), comparer);

    }
    catch (IndexOutOfRangeException)
    {
        ...
        throw new ArgumentException(Environment.GetResourceString("Arg_BogusIComparer", values));
    }
}

Going a little further into the QuickSort implementation, you see this code:

    while (comparer.Compare(keys[a], y) < 0)
    {
        a++;
    }
    while (comparer.Compare(y, keys[b]) < 0)
    {
        b--;
    }

, IComparer Quicksort IndexOutOfRangeException, n ArgumentException.

IComparer

class Comparer: IComparer<int>
{
    public int Compare(int x, int y)
    {
        return -1;
    }
}

, , , , IComparer , :

, , , , .

+3

, , x y, , 0. , .

,

+2

All Articles