임의의 정수가 저장된 변수 a, b, c의 대소관계의 경우의 수는 13개입니다.
이를 순서대로 판단하기 위해서는 결정트리 형태를 생각할 수 있습니다.
if - else if를 이용해 대소관계를 판단할 수 있음을 예상할 수 있습니다.
연습문제 Q4
import java.util.Scanner;
public class Practice {
static int med3(int a, int b, int c) {
if(a>=b) {
if(b>=c) {
return b;
}
else if (a<=c) {
return a;
}
else {
return c;
}
}
else if(a>c) {
return a;
}
else if(b>c) {
return c;
}
else {
return b;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("med of (1,2,3) is "+med3(1,2,3));
System.out.println("med of (1,3,2) is "+med3(1,3,2));
System.out.println("med of (2,1,3) is "+med3(2,1,3));
System.out.println("med of (2,3,1) is "+med3(2,3,1));
System.out.println("med of (3,1,2) is "+med3(3,1,2));
System.out.println("med of (3,2,1) is "+med3(3,2,1));
System.out.println("med of (1,1,2) is "+med3(1,1,2));
System.out.println("med of (1,2,1) is "+med3(1,2,1));
System.out.println("med of (2,1,1) is "+med3(2,1,1));
System.out.println("med of (2,2,1) is "+med3(2,2,1));
System.out.println("med of (2,1,2) is "+med3(2,1,2));
System.out.println("med of (1,2,2) is "+med3(1,2,2));
}
}
연습문제 Q5
첫번째 if를 만족하면 두번째 if에서 실질적으로 거의 같은 판단(b>=a 와 a<b, b<=a와 a>b)을 한번 더 수행하게 되므로 비효율적이다. 실습 1C-1에서는 트리형식으로 판단하므로 같은 판단을 또 수행하지 않는다.
이미지 출처 : C언어로 배우는 알고리즘과 자료구조 - 제 1장 :: Burn the bug (tistory.com)
C언어로 배우는 알고리즘과 자료구조 - 제 1장
번역 공부 1. 제 1 장 기본적인 알고리즘 1-1 알고리즘이란? [최대값 구하기] 간단한 프로그램을 예로, 알고리즘에 대해서 생각해 봅시다. List 1-1 은 3개의 정수 중 가장 큰 숫자를 구하는 프로그
burnthebug.tistory.com
'Do it! 자료구조와 함께 배우는 알고리즘 입문 (자바)' 카테고리의 다른 글
보충수업 1-1 : 자바(java)에서 키보드로 숫자와 문자열 입력하기(1) - Scanner (0) | 2022.01.17 |
---|---|
1. 기본 알고리즘 - 알고리즘이란? (연습문제 Q1~Q3) (0) | 2022.01.17 |