Slow but steady wins the race

[알고리즘] 최댓값 구하기 - java 본문

Programming Language/자료구조와 알고리즘

[알고리즘] 최댓값 구하기 - java

BS Kwak 2021. 2. 11. 04:48

3개의 정수 값 중 최댓값을 구하는 프로그램

 

코드를 먼저 보여주자면

import java.util.Scanner;
public class Max3 {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);

        System.out.print("a: "); int a = sc.nextInt();
        System.out.print("b: "); int b = sc.nextInt();
        System.out.print("c: "); int c = sc.nextInt();

        int max = a;
        if(b>max) max=b;
        if(c>max)  max=c;

        System.out.println("max : "+max);
        sc.close();
    }
}

 

정수 a,b,c를 입력받고, 최댓값(max)을 찾아낸다. 알고리즘(과정)은 다음과 같다. 

1. max 변수에 a값을 대입한다.

2. b값이 max값보다 클 경우, max값에 b값을 대입한다.

3. c값이 max값보다 클 경우, max값에 c값을 대입한다.

 

이렇게 여러 process(문장)들이 순차적으로 진행되는 구조를 순차적 구조(concatenation structure)라 한다. 

a=5, b=8, c=3 이라고 가정해보자. 위 코드를 실행시켜보면

1. max =5

2. (b>max)? true이므로 max = 8

3. (c>max)? false이므로 max = 8

 

참고로, 코드를 짤 때는 위와 같이 main 클래스 안에 해당 알고리즘을 구현하는 것보다 아래와 같이 하나의 메소드(method)를 새로 만들어 구현하는 것이 좋다.

public class Max3 {
    static int max(int a,int b, int c){
        int max = a;
        if(b>max) max=b;
        if(c>max)  max=c;

        return max;
    }
    public static void main(String[] args){
        
        System.out.println("max(5,8,3)="+max(5,8,3));
    }
}

 

3개뿐만아니라 4개,5개,,, 모두 동일한 방식으로 적용할 수 있다.

해당 정수들을 배열로 입력받았다면??

어려울 것 없다. 똑같이 하면된다. 

배열의 첫번째 요소를 max변수에 대입한 후에, 두번째요소, 세번째요소, 등과 비교하면서 큰 값을 max에 대입하면 된다.

import java.util.Scanner;
public class MaxOfArray {
    static int maxOfArray(int []a){
        int max = a[0];
        for(int i=0;i<a.length;i++){
            if(a[i]>max)    max=a[i];
        }

        return max;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];

        for(int i=0;i<n;i++){
            arr[i]=sc.nextInt();
        }
        System.out.println("max="+maxOfArray(arr));
    }
}

 

Comments