Shibaku Shibaku - 1 year ago 61
Java Question

How to find the median of five user-input numbers without using array?

The title pretty much sums up my question. How do I find the median of five user-input numbers without using arrays?

The only way I can think of doing this is by using multiple if-statements.
Even then, I wouldn't be quite sure where to start with that.

Any help or advice would be appreciated, thank you!

Answer Source

I like the idea of using multiple if-else statements. I took inspiration from this question and wrote the following. It gives an awful lot of code, so it’s probably not the best solution, but proves it can be done.

/** @return the median, that is, the 3rd greatest, of the arguments */
public static int median(int a, int b, int c, int d, int e) {
    // sort a and b
    int ab1, ab2;
    if (a < b) {
        ab1 = a;
        ab2 = b;
    } else {
        ab1 = b;
        ab2 = a;
    assert ab1 <= ab2;
    // c and d
    int cd1, cd2;
    if (c < d) {
        cd1 = c;
        cd2 = d;
    } else {
        cd1 = d;
        cd2 = c;
    assert cd1 <= cd2;
    // from a through d find i1 <= i2 <= i3 and j <= i3
    // however, discard i3 since it is to great to be the median
    int i1, i2, j;
    if (ab2 < cd2) {
        i1 = ab1;
        i2 = ab2;
        j = cd1;
    } else {
        i1 = cd1;
        i2 = cd2;
        j = ab1;
    assert i1 <= i2;
    // we need to find the 2nd greatest of i1, i2, j and e
    // sort j and e
    int je1, je2;
    if (j < e) {
        je1 = j;
        je2 = e;
    } else {
        je1 = e;
        je2 = j;
    assert je1 <= je2;
    if (i2 < je2) {
        // je2 is too great to be a median
        // find the greates of i1, i2 and je1
        // knowing that i1 <= i2 this can be accomplished by:
        return Math.max(i2, je1);
    } else {
        // discard i2 as too great
        return Math.max(i1, je2);

Edit: I have simplified a bit compared to the first version I posted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download