Java | 수 정렬하기 [백준 2750]

나경호·2022년 4월 10일
0

알고리즘 Algorithm

목록 보기
77/106

수 정렬하기

출처 | 수 정렬하기 [백준 2750]

문제

N개의 수가 주어졌을 때, 이를 오름차순으로 정렬하는 프로그램을 작성하시오.

입력

첫째 줄에 수의 개수 N(1 ≤ N ≤ 1,000)이 주어진다. 둘째 줄부터 N개의 줄에는 수 주어진다. 이 수는 절댓값이 1,000보다 작거나 같은 정수이다. 수는 중복되지 않는다.

출력

첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.


풀이[Arrays 메소드]

import java.io.*;
import java.util.*;

public class Main{

    
	public static void main(String[] args) throws IOException{

        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(scan.readLine());
        int [] arr = new int [N];
        
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(scan.readLine());
        }
        StringBuilder sb = new StringBuilder();
       
        Arrays.sort(arr);
        
        for (int i = 0; i < N; i++) {
            sb.append(arr[i] + "\n"); 
        }

        System.out.print(sb);

    }
}

풀이[정렬 알고리즘]

import java.io.*;
import java.util.*;

public class Main{

    
	public static void main(String[] args) throws IOException{

        BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(scan.readLine());
        int [] arr = new int [N];
        
        for (int i = 0; i < N; i++) {
            arr[i] = Integer.parseInt(scan.readLine());
        }
        StringBuilder sb = new StringBuilder();
        // 가장 작은 수를 앞으로
        for (int i = 0; i < N; i++) {
            for (int j = i; j < N; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
            sb.append(arr[i] + "\n");
        }

        System.out.print(sb);

    }
}

출처

  • 문제의 오타를 찾은 사람: lazy_ren

비슷한 문제

알고리즘 분류

profile
기억창고👩‍🌾

0개의 댓글