Sunday, April 4, 2010

sort3

A snippet from my latest question on stackoverflow "Reordering arguments using recursion (pro, cons, alternatives)", what I honestly believe is the most elegant solution one can write for sorting 3 values:
// sorts 3 values and return as array
static int[] sort3(int a, int b, int c) {
    return
      (a > b) ? sort3(b, a, c) :
      (b > c) ? sort3(a, c, b) :
      new int[] { a, b, c };
}
So far, most people say that the code is unreadable. Which is rather sad, actually.

I hope I won't ever have to dumb down my work for stupid people.

3 comments:

  1. I think people are uncomfortable with the precedence of the ternary operator because they've probably gotten bitten by something like "a == b ? x : y" before. So, just adding some redundant parentheses around the 2nd ternary operator would help a lot (until the idiom became more common at least).

    ReplyDelete
  2. Also, one thing that bothers me a bit about these recursive solutions is that they necessary involve an extra check of the condition when you already know what the answer is. So, I think I would prefer something done in terms of helper functions that assume the condition is met. They are admirably concise though.

    ReplyDelete
  3. You are right about the extra checks on conditions that should already be known to be true, but as Donald Knuth says, "We should forget about small efficiencies, say about 97% of the time".

    I *think* it applies in this case.

    ReplyDelete