0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

三つの値の中央値

Posted at

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パターンあるため、それぞれのパターンで呼び出してみました。

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

0
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?