
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));
}
}