Effectively disable Sort() within a CompareTo() override?
Asked Answered
M

3

6

The CompareTo() method for my class is dynamic, and can range from a simple comparison to comparisons on a number of columns. This is all determined at run time, and it works great.

But in some cases, I want any attempt to sort a collection of my objects using the default comparison to just do nothing.

Having CompareTo() just return a 0 for any comparison, to my surprise, doesn't work. The list gets rearranged in some odd, seemingly-random order.

Is there a way to do this in the CompareTo() method implementation? I'd rather not handle this up at the collection level by having to override Sort().

Marc answered 9/3, 2010 at 23:24 Comment(0)
L
1

That's because QuickSort is not a stable sort. I don't see a good option to fix this in the CompareTo method unless you can somehow obtain the index of the element.

Lily answered 9/3, 2010 at 23:45 Comment(1)
Thanks, makes perfect sense. I expected that was the case, but Data Algorithms class was so long ago...Marc
M
0

I haven´t proved it, but as a suggestion, what if you try to return always 1, or always -1?

Murex answered 9/3, 2010 at 23:30 Comment(1)
This violates the properties of the CompareTo method: If A.CompareTo(B) returns a value other than zero, then B.CompareTo(A) is required to return a value of the opposite sign.Actinouranium
A
0

You have to override Sort(). The default implementation of Sort() offers no guarantees about how it will use CompareTo() to arrive at a sorted collection, so there isn't any way to use it to make Sort() do the right thing.

Alps answered 9/3, 2010 at 23:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.