알고리즘
[알고리즘] 버블정렬 (Bubble Sort) Java Example
개쿠
2019. 6. 23. 15:29
728x90
반응형
버블 정렬 알고리즘
버블 정렬(Bubble Sort) 알고리즘은 원소가 뒤에서 부터 정렬되는 알고리즘입니다.
- 인접한 두 원소를 검사하여 정렬하는 알고리즘
- 간단한 알고리즘
- 성능 향상 알고리즘으로 준비
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
public class Bubble_Sort {
public static void main(String[] args) {
int[] arr = { 10, 50, 80, 90, 70 };
// 배열의 길이 -1
int size = arr.length -1;
boolean flag;
for (int i = 0; i < size; i++) {
// 교환이 있었는지 체크하는 변수
flag = false;
// 맨 뒤 부터 정렬 되기 때문 i만큼 뺀다
for (int j = 0; j < size - i; j++) {
if (arr[j] > arr[j + 1]) {
// 교환이 발생하여 true 로 변경
flag = true;
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
// 원소 교환이 없으므로 정렬을 더 이상 할 필요 없다.
if (flag == false) {
break;
}
}
output(arr);
}
private static void output(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4f; text-decoration:none">Colored by Color Scripter
|
728x90
반응형