Post

BubbleSort_오름차순으로 정렬하기

🔵 ThingsILearned

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

⭐️ 한번 사이클을 돌 때마다 가장 큰 수가 마지막으로 간다는게 포인트

Screenshot 2024-08-26 at 00 30 32

✅ 버블정렬로 수 배열을 오름차순으로 정렬하세요

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

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

    for(int i=0; i<n-1; i++){ //사이클 횟수
        for(int j=0; j<n-i-1; j++){ //처음 숫자랑 그 다음 숫자랑 비교하기
            int nextNum= j+1; //다음 숫자
            if(input[j]> input[nextNum]){
                int tmp= input[nextNum];
                input[nextNum]= input[j];
                input[j] = 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. 첫번째 원소와 두번째 원소를 비교합니다.
  2. 두번째 원소가 가 더 큰 경우, 두 원소를 서로 교환(Swap)합니다.
  3. 위 과정을 마지막 원소를 만날 때까지 실행합니다.
  4. 위 과정을 모두 마치고 나면 마지막 원소는 가장 큰 값이 되어있습니다.
  5. 값이 정해진 마지막 원소를 제외하고 1~4번 과정을 다시 반복합니다.

🟢 같은 버블정렬, 다른 코드

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){


            int i=0;
            while(n>0) {
                while (i < n - 1) {
                    int j = i + 1;
                    if (input[i] > input[j]) { //이웃한 두 수끼리 비교
                        int tmp = input[i];
                        input[i] = input[j];
                        input[j] = tmp;
                    }
                    i++;
                }
                n--;
                i=0;
            }

        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+ " ");
       }
    }
}
This post is licensed under CC BY 4.0 by the author.