CS/알고리즘
[정렬] 버블정렬
지잉지잉
2021. 8. 28. 15:30
버블정렬 (Bubble Sort)
- 인접한 두개의 원소를 비교, 자리를 교환하는 정렬방식.
- 구현
public class Main {
public static void main(String[] args) {
int[] array = {2, 4, 3, 5, 1};
int length = array.length;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
- 배열의 길이만큼의 for문을 2번돌리기에 시간복잡도는 O(N^2)