1. 정렬 (sorting) 이란?
정렬 (sorting) : 어떤 데이터들이 주어졌을 때 이를 정해진 순서대로 나열하는 것
정렬은 프로그램 작성시 빈번하게 필요로 함
2. 버블 정렬 (bubble sort)
두 인접한 데이터를 비교해서, 앞에 있는 데이터가 뒤에 있는 데이터보다 크면 자리를 바꾸는 정렬 알고리즘
- [5, 2] -> [2, 5]
- [5, 4, 2] -> [4, 5, 2] -> [4, 2, 5]
-> [2, 4, 5] - [5, 2, 3, 1] -> [2, 5, 3, 1] -> [2, 3, 5, 1] -> [2, 3, 1, 5]
-> [2, 3, 1, 5] -> [2, 1, 3, 5]
-> [1, 2, 3, 5]
import java.util.*;
public class BubbleSort {
public static void bubbleSort() {
int[] arr = new int[5];
int size = arr.length;
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
arr[i] = sc.nextInt();
}
System.out.println("정렬 전 : " + arr);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("정렬 후 : " + arr);
}
}
3. 알고리즘 분석
반복문이 두개 : O(n^2)
완전 정렬이 되어 있는 경우 : O(n)
'Algorithm > 알고리즘' 카테고리의 다른 글
그래프(Graph) (0) | 2023.01.23 |
---|---|
동적 계획법 (Dynamic Programming)과 분할 정복 (Divide and Conquer) (0) | 2023.01.20 |
재귀 용법 (recursive call) (0) | 2023.01.20 |
선택 정렬 (selection sort) (0) | 2023.01.19 |
삽입 정렬 (insertion sort) (0) | 2023.01.19 |