Help us understand the problem. What is going on with this article?

三つの値の中央値

More than 1 year has passed since last update.

Java による三つの値の中央値の求め方の例

最近「Javaで学ぶアルゴリズムとデータ構造」を読み始め、三つの値の中央値を求める演習問題を解きました。
メモっておくと後々役に立ちそうだったので書いておきます。

    public static void main(String[] args) {
        System.out.println(med3(3, 2, 1)); // [A] a > b > c
        System.out.println(med3(3, 2, 2)); // [B] a > b = c
        System.out.println(med3(3, 1, 2)); // [C] a > c > b
        System.out.println(med3(3, 2, 3)); // [D] a = c > b
        System.out.println(med3(2, 1, 3)); // [E] c > a > b
        System.out.println(med3(3, 3, 2)); // [F] a = b > c
        System.out.println(med3(3, 3, 3)); // [G] a = b = c
        System.out.println(med3(2, 2, 3)); // [H] c > a = b
        System.out.println(med3(2, 3, 1)); // [I] b > a > c
        System.out.println(med3(2, 3, 2)); // [J] b > a = c
        System.out.println(med3(1, 3, 2)); // [K] b > c > a
        System.out.println(med3(2, 3, 3)); // [L] b = c > a
        System.out.println(med3(1, 2, 3)); // [M] c > b > a

    }

    private static int med3(int a, int b, int c) {
        if (a >= b) {
            if (b >= c) {
                return b; // A, B, F, G
            } else if (a <= c) {
                return a; // D, E, H
            } else {
                return c; // C
            }
        } else if (a > c) {
            return a; // I
        } else if (b > c) {
            return c; // J, K
        } else {
            return b; // L, M
        }
    }

三つの値の大小関係には13パターンあるため、それぞれのパターンで呼び出してみました。

中央値の求め方には他にもいろいろとあると思いますので、あくまでも一例として参考にしてください。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした