Post

Selection sort_오름차순으로 정렬하기

🔵 ThingsILearned

✔️ Selection sort: complexity of O(n^2)

✅ 선택정렬

N개의 숫자가 입력되면 오름차순으로 정렬
선택정렬 사용하기

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
class Main {

    public int[] solution(int n, int[] input){

        for(int i=0; i<n-1; i++){
            int idx= i; //가장 작은 값이 있는 인덱스 초기화
            for(int j=i+1; j<n; j++){ //j는 i다음부터 돈다.
                if(input[j] < input[idx]){
                    idx=j; //제일 작은 값 있는 인덱스 저장
                }
            }
            int tmp= input[i]; //제일 작은 인덱스에 있는 숫자랑 맨 앞에 있는 i랑 바꿔줌
            input[i] = input[idx];
            input[idx]= tmp;
        }
        return input;
    }
    public static void main(String[] args) {
        Main T = new Main();
        Scanner sc= new Scanner(System.in);
        int n= sc.nextInt();
        int[] input= new int[n];
        for(int i=0; i<n; i++){
            input[i]= sc.nextInt();
        }
       for(int i: T.solution(n, input)) {
           System.out.print(i+ " ");
       }
    }
}
//⭐️input:
6
13 5 11 7 23 15
//⭐️output:
5 7 11 13 15 23
  1. i는 처음부터, j는 i다음부터 돌기
  2. 첫 번째 값이랑, 두번째 값부터 마지막 값이랑 비교하여 가장 작은 값을 첫 번째에 두기
  3. 그리고 두 번째 값이랑 세 번째 값부터 마지막 값이랑 비교하여 가장 작은 값을 두 번째에 두기
  4. 반복

코딩공책-44

Screenshot 2024-08-26 at 00 34 18

This post is licensed under CC BY 4.0 by the author.