데이터의 인접 요소끼리 비교하고, swap 연산을 수행하며 정렬하는 방식
만약 특정한 루프의 전체 영역에서 swap이 한 번도 발생하지 않았다면 그 영역 뒤에 있는 데이터가 모두 정렬됐다는 뜻이므로 프로세스를 종료해도 됨
public class BubbleSort {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = readInt();
int[] A = new int[N];
for (int i = 0; i < N; i++) A[i] = readInt();
for (int i = 0; i < N - 1; i++) {
int swapCnt = 0;
for (int j = 0; j < N - 1 - i; j++) {
if (A[j] > A[j + 1]) {
swapCnt++;
int tmp = A[j];
A[j] = A[j + 1];
A[j + 1] = tmp;
}
}
if (swapCnt == 0) break;
}
for (int i = 0; i < A.length; i++) {
bw.write(A[i] + "");
bw.newLine();
}
bw.flush();
bw.close();
}
static int readInt() throws IOException {
int n = 0;
boolean isNegative = false;
while (true) {
int input = System.in.read();
if (input <= 32) {
return isNegative ? n * -1 : n;
} else if (input == '-')
isNegative = true;
else
n = (n << 3) + (n << 1) + (input & 15);
}
}
}
ref : Do It 알고리즘 코딩테스트 자바편 by 김종관