버블 정렬이란?
서로 이웃한 데이터를 비교해 큰 수를 뒤로 보내고 작은 수를 앞으로 보내는 정렬
ex) 15, 1 -> 1, 15
#include <stdio.h>
int main(void) {
int i, j, temp;
int arr[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
for(i=0; i<10; i++){
for(j=0; j < 9-i; j++){
if(arr[j] > arr[j + 1]){
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for(i=0; i<10; i++){
printf("%d ", arr[i]);
}
return 0;
}
시간복잡도 또한 O(N^2)
자바
public class BubbleSort {
public static void main(String[] args) {
int[] array = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int temp;
for(int i=1; i<= array.length; i++){
for(int j=0; j< array.length-i; j++){
if(array[j] > array[j+1]){
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for(int i=0; i<array.length; i++){
System.out.printf("%d ", array[i]);
}
}
}
'알고리즘 > 여러가지' 카테고리의 다른 글
[백준] 2480 주사위 세개 (0) | 2022.05.13 |
---|---|
unordered_map VS map c++ (1) | 2021.05.08 |
선택정렬 (Selection Sort) (0) | 2021.04.27 |