-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort2.java
More file actions
48 lines (40 loc) · 1.1 KB
/
BubbleSort2.java
File metadata and controls
48 lines (40 loc) · 1.1 KB
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
40
41
42
43
44
45
46
47
48
package sort;
import java.util.Scanner;
// 버블 정렬(버전 2)
public class BubbleSort2 {
// a[idx1]와 a[idx2]의 값을 바꾼다
static void swap(int[] a, int idx1, int idx2) {
int t = a[idx1];
a[idx1] = a[idx2];
a[idx2] = t;
}
// 버블 정렬
static void bubbleSort(int[] a, int n) {
for(int i=0; i<n-1; i++) {
int exchg = 0; // 패스의 교환 횟수를 기록
for(int j=n-1; j>i; j--) {
if(a[j-1] > a[j]) {
swap(a, j-1, j);
exchg++;
}
}
if(exchg == 0) break; // 교환이 이루어지지 않으면 종료
}
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("버블 정렬(버전 2)");
System.out.print("요솟 수 : ");
int nx = stdIn.nextInt();
int[] x = new int[nx];
for(int i=0; i<nx; i++) {
System.out.print("x[" + i + "] : ");
x[i] = stdIn.nextInt();
}
bubbleSort(x, nx); // 배열 x를 버블 정렬합니다
System.out.println("오름차순으로 정렬했습니다.");
for(int i=0; i<nx; i++)
System.out.println("x[" + i + "]= " + x[i]);
stdIn.close();
}
}