두 인접한 데이터의 크기를 비교해 정렬하는 방법으로 시간복잡도는 O(n²)이지만, 간단하게 구현할 수 있어 자주 사용한다.
public class Main {
public static void main(String[] args) {
int[] arr = new int[] {5, 4, 1, 3, 2};
arr = bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
static int[] bubbleSort(int[] arr) {
for(int i = 0; i < arr.length - 1; i++) {
for(int j = 1; j < arr.length - i; j++) {
// 앞 인덱스 데이터와 뒷 인덱스 데이터와 비교해서 앞이 더 크면 위치 변경
if(arr[j] < arr[j-1]) {
int tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
}
}
}
}
제자리 정렬(In-Place Sort)이다.
버블 정렬은 간단한 만큼 빠른 속도로 수행되지 않아 효율적으로 알고리즘을 짜야하는 경우에는 거의 사용되지 않는다.

첫째 줄부터 N개의 줄에 오름차순으로 정렬한 결과를 한 줄에 하나씩 출력한다.
1초
버블 정렬을 활용해 정렬해보자.
- Java에서 제공하는 정렬을 하면 되지만 버블 정렬 공부를 위해 버블 정렬을 통해 정렬을 해보자.
시간 초과는 고려할 사항이 아니다.
- N이 1,000개이기 때문에 이중으로 반복을 수행해도 1,000,000이기 때문에 시간 초과를 생각해야할 문제는 아니다.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n+1];
for(int i = 1; i < n+1; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
bubbleSort(n, arr);
StringBuilder sb = new StringBuilder();
for(int i = 1; i < n+1; i++) {
sb.append(arr[i]).append("\n");
}
System.out.println(sb);
}
static void bubbleSort(int n, int[] arr) {
for(int i = 1; i <= n+1; i++) {
for(int j = 1; j <= n-i; j++) {
if(arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}