int[] arr = {5, 3, 8, 4, 2};

์ด ๋ฐฐ์—ด์„ ๋ฒ„๋ธ”์ •๋ ฌ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ๋ฐฐ์—ดํ•˜๊ธฐ. 

 

์˜ˆ์‹œ ์ถœ๋ ฅ : 

Before Sorting: [5, 3, 8, 4, 2] After Sorting: [2, 3, 4, 5, 8]

<๋‚˜์˜ ์ฝ”๋“œ>

package Array;

import java.util.Arrays;

public class BubbleSort {
    public static void bubbleSort (int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n-1; i++) {
            boolean swapped = false;
            for(int j = 0; j < n-1-i; j++) {
                if (int[j] > int[j+1]) {
                    int temp = int[j];
                    int[j] = int[j+1];
                    int[j+1] = int[j];
                    swapped = true;
                }
            }
            if(!swapped) break;
        }
    }
}

  <์ฑ„์ >

๋ฌธ์ œ์  1: int[j]์™€ int[j+1]์˜ ์‚ฌ์šฉ

 - int[j]์™€ int[j+1]๋Š” ์˜ฌ๋ฐ”๋ฅธ ๋ฌธ๋ฒ•์ด ์•„๋‹ˆ๋‹ค.

   int๋Š” ๋ฐฐ์—ด์˜ ํƒ€์ž…์„ ๋‚˜ํƒ€๋‚ด๋Š”ํ‚ค์›Œ๋“œ์ด๋ฏ€๋กœ, ๋ฐฐ์—ด์˜ ์š”์†Œ์— ์ ‘๊ทผํ•˜๋ ค๋ฉด ๋ฐฐ์—ด ์ด๋ฆ„์„ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

- ์˜ฌ๋ฐ”๋ฅธ ์‚ฌ์šฉ : arr[j] ์™€ arr[j+1].

 

๋ฌธ์ œ์  2: ์ค‘๋ณต ๋Œ€์ž…

int temp = int[j];
int[j] = int[j+1];
int[j+1] = int[j]; // ์ž˜๋ชป๋œ ๋Œ€์ž…

์„ธ๋ฒˆ์งธ ์ค„์— ์„ค์ •ํ•œ ๋ณ€์ˆ˜๋ฅผ ๋„ฃ์–ด์•ผ ํ•œ๋‹ค.

int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;

 

 

๋ฌธ์ œ์  3: ๋ฐฐ์—ด ์ถœ๋ ฅ ๋ˆ„๋ฝ

   - ์ •๋ ฌ๋œ ๋ฐฐ์—ด์„ ํ™•์ธํ•˜๋ ค๋ฉด System.out.println์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•ด์•ผ ํ•œ๋‹ค.

   main ๋ฉ”์„œ๋“œ์—์„œ ๋ฐฐ์—ด์„ ์ •๋ ฌํ•œ ํ›„ ์ถœ๋ ฅํ•˜๋„๋ก ์ถ”๊ฐ€ํ•˜์ž.

public static void main(String[] args) {
   int[] arr = {5,, 3, 8, 4, 2};
   System.out.println("Before Sorting: " + Arrays.toString(arr));
   bubbleSort(arr);
   System.out.println("After Sorting" + Arrays.toString(arr));
}

 


<์ •๋‹ต ์ฝ”๋“œ>

package Array;

import java.util.Arrays;

public class BubbleSort {
    public static void bubbleSort(int[] arr) {
        int n = arr.length;

        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }
            if (!swapped) break;
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 4, 2};
        System.out.println("Before Sorting: " + Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println("After Sorting: " + Arrays.toString(arr));
    }
}

+ Recent posts