How do I calculate the “median of five” in C#?

后端 未结 10 2071
遇见更好的自我
遇见更好的自我 2020-12-04 22:05

The median of five is sometimes used as an exercise in algorithm design and is known to be computable using only 6 comparisons.

What is the best way

10条回答
  •  死守一世寂寞
    2020-12-04 22:59

    An interesting thread here:

    http://www.ocf.berkeley.edu/~wwu/cgi-bin/yabb/YaBB.cgi?board=riddles_cs;action=display;num=1061827085

    Quote from thread:

    1. Put the numbers in an array.

    2. Use three comparisons and shuffle around the numbers so that a[1] < a[2], a[4] < a[5], and a[1] < a[4].

    3. If a[3] > a[2], then the problem is fairly easy. If a[2] < a[4], the median value is the smaller of a[3] and a[4]. If not, the median value is the smaller of a[2] and a[5].

    4. So a[3] < a[2]. If a[3] > a[4], then the solution is the smaller of a[3] and a[5]. Otherwise, the solution is the smaller of a[2] and a[4].

提交回复
热议问题