8

In a sortedlist queue, queue.value[0] gives the corresponding value of a min key. what if i would like to make that it gives the value of a max key?

Do i have to rewrite the icomparer?

aloisdg
  • 16,342
  • 4
  • 73
  • 80
colinfang
  • 17,887
  • 11
  • 69
  • 146
  • If you are only interrested in the maximum key, the list is big and performance is key, you should check out priority queues (http://stackoverflow.com/questions/102398/priority-queue-in-net) – larsmoa Jun 01 '11 at 09:47
  • @larsm - I thought priority queues were implemented in C# using sortedlist/sortedddirectionary. Is it not true? – colinfang Jun 01 '11 at 13:35
  • That would be a bad implementation. A priority queue only requires the first item top be the min/max element, it has no requirements on the remaining items in the list. By exploiting this, a priority queue is potentially a much more efficient data container than a fully sorted list/dictionary. Typically, priority queues are implemented using heaps (see http://en.wikipedia.org/wiki/Priority_queue#Naive_implementations) – larsmoa Jun 01 '11 at 13:42

4 Answers4

13

Yes you have to rewrite the comparer

example for string as key: (just exchanged x.CompareTo(y) with y.CompareTo(x) )

private class InvertedComparer : IComparer<String>
    {
        public int Compare(string x, string y)
        {
            return y.CompareTo(x);
        }
    }

and the call:

SortedList<string, Object> list = new SortedList<string, Object>(new InvertedComparer());
fixagon
  • 5,336
  • 19
  • 25
1

Here's a link to an article that implements a ReversibleSortedList. This allows for changing the sort direction.

In case you always want reversed sort behavior without the ability to change it on demand, I'd try the constructor that accepts an IComparer.

takrl
  • 6,098
  • 3
  • 55
  • 64
1

Just use Array.Reverse() in some simple cases.

using System;

class Program
{
    static void Main()
    {
    // Input array.
    int[] array = { 1, 2, 3 };

    // Print.
    foreach (int value in array)
    {
        Console.WriteLine(value);
    }
    Console.WriteLine();

    // Reverse.
    Array.Reverse(array);

    // Print.
    foreach (int value in array)
    {
        Console.WriteLine(value);
    }
    Console.WriteLine();

    // Reverse again.
    Array.Reverse(array);

    // Print.
    foreach (int value in array)
    {
        Console.WriteLine(value);
    }
    }
}

* Output *

1
2
3

3
2
1

1
2
3
goldengel
  • 591
  • 7
  • 22
0

You could just invert any existing IComparers. Something like:

public static IComparer<T> Invert<T>(this IComparer<T> comparer)
{
    return Comparer<T>.Create((x, y) => comparer.Compare(y, x));
}

And use your regular comparer. For e.g.

new SortedList<,>(myShinyComparer.Invert());
nawfal
  • 62,042
  • 48
  • 302
  • 339