https://swexpertacademy.com/main/solvingProblem/solvingProblem.do

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

오름차순으로 정렬하는 것이므로 두 가지 방식으로 풀어보고자 한다.

1. 버블 정렬

2. 선택 정렬

 

Theme. 버블 정렬 Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        int T = sc.nextInt();
        for (int n = 1; n <= T; n++) {
            int tmp;
            int t = sc.nextInt();
            int[] arr = new int[t];
            for (int i = 0; i < t; i++) {
                arr[i] = sc.nextInt();
            }
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    if (arr[j] > arr[j + 1]) {
                        tmp = arr[j + 1];
                        arr[j + 1= arr[j];
                        arr[j] = tmp;
                    }
                }
            }
 
            System.out.print("#" + n + " ");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
            System.out.println();
        }
    }
 
}
 
cs

 

Theme. 선택 정렬 Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.util.Scanner;
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
 
        int T = sc.nextInt();
        for (int n = 1; n <= T; n++) {
            int tmp;
            int t = sc.nextInt();
            int[] arr = new int[t];
            for (int i = 0; i < t; i++) {
                arr[i] = sc.nextInt();
            }
            for (int i = 0; i < arr.length - 1; i++) {
                int minIdx = i;
                for (int j = i+1; j < arr.length; j++) {
                    if (arr[minIdx] > arr[j]) {
                        minIdx = j;
                    }
                }
                tmp = arr[minIdx];
                arr[minIdx] = arr[i];
                arr[i] = tmp;
            }
 
            System.out.print("#" + n + " ");
            for (int i = 0; i < arr.length; i++) {
                System.out.print(arr[i] + " ");
            }
            System.out.println();
        }
    }
 
}
cs

 

 

 

+ Recent posts