Is it possible to override the comparator < in C#?

  • Topic: C# 
  • Thread starter Thread starter SlurrerOfSpeech
  • Start date Start date
  • Tags Tags
    Comparator
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
7 replies · 2K views
SlurrerOfSpeech
Messages
141
Reaction score
11
Is it possible to override the < operator in C#? Note: I'm saying override, not overload.

I ask because, if there is, then I think I have discovered an O(1) sorting algorithm.
 
Physics news on Phys.org
SlurrerOfSpeech said:
Is it possible to override the < operator in C#? Note: I'm saying override, not overload.

I ask because, if there is, then I think I have discovered an O(1) sorting algorithm.
I'm not certain, but I don't think it is possible.According to the C# docs here, the base class would need to have a virtual < operator that you would override in your derived class. If you are comparing ordinary number values, the C# types for Int16, Int32, and Int64 don't have any operators defined on these structs. The Single (32-bit floating point) and Double (64-bit floating point) types do have operators defined for <, >, and so on, but these are public static operators, not virtual.
 
I am a bit puzzled about how you can image a sorting algorithm in general (that is, not only in a narrow special case, like if we know all elements are already sorted) can perform as O(1) considering it has to read each of the N element at least once. I am also puzzled why you think the existence of such an algorithm should relate to whether or not it is possible to override the less-than operator in C#. Can you perhaps explain what you mean in more detail?
 
Filip Larsen said:
I am a bit puzzled about how you can image a sorting algorithm in general (that is, not only in a narrow special case, like if we know all elements are already sorted) can perform as O(1) considering it has to read each of the N element at least once.

If I can redefine the meaning of < then I can ensure that an array is sorted without looking at any of its elements
 
SlurrerOfSpeech said:
If I can redefine the meaning of < then I can ensure that an array is sorted without looking at any of its elements
Maybe your code doesn't have to look at the elements of the array. But then you rely on some feature of the compiler with the overridden < to sort the array. And that will not be O(1).
 
  • Like
Likes   Reactions: FactChecker
SlurrerOfSpeech said:
If I can redefine the meaning of < then I can ensure that an array is sorted without looking at any of its elements

Can you please explain how you plan to sort an array of elements without looking at the elements themselves? And by "sort" I am referring to its usual meaning, like explained at [1].

[1] https://en.wikipedia.org/wiki/Sorting_algorithm