Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Dec 3, 2015 #1
    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.
     
  2. jcsd
  3. Dec 3, 2015 #2

    Mark44

    Staff: Mentor

    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.
     
  4. Dec 3, 2015 #3

    Filip Larsen

    User Avatar
    Gold Member

    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?
     
  5. Dec 3, 2015 #4
    If I can redefine the meaning of < then I can ensure that an array is sorted without looking at any of its elements
     
  6. Dec 3, 2015 #5

    Samy_A

    User Avatar
    Science Advisor
    Homework Helper

    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).
     
  7. Dec 3, 2015 #6

    Filip Larsen

    User Avatar
    Gold Member

    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
     
  8. Dec 7, 2015 #7

    Vanadium 50

    User Avatar
    Staff Emeritus
    Science Advisor
    Education Advisor

    Folks, I am afraid the OP is trolling us. (He's admitted this in another thread)
     
  9. Dec 7, 2015 #8

    DrClaude

    User Avatar

    Staff: Mentor

    Nothing more to say here. Thread closed.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook