petrush petrush - 1 month ago 11
C# Question

How to implement CompareTo for arrays?

I have the following class

public class MinPQ<T> : IComparable<T>
{
private T[] keys;
...
}


How to implement
CompareTo
method? I would like to do the following in my method

public void decreaseKey(int i, T key){
if (keys[i].CompareTo(key) <= 0) {...} // or if(CompareTo(keys[i], key) <= 0)
}


Most of the time
T
will be
int
or
double

Answer

I assume that you mean how to declare the type T as comparable. If so, you can do it with the following generic constraint.

public class MinPQ<T> where T: IComparable<T>
{
    private T[] keys;
    ...
}