-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
56 lines (47 loc) · 1.49 KB
/
Copy pathMergeSort.java
File metadata and controls
56 lines (47 loc) · 1.49 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
49
50
51
52
53
54
55
56
import java.util.*;
/**
* MergeSort Algorithm Implementation
* 합병 정렬 구현
*/
public class MergeSort {
/**
* 리스트를 반으로 분할하고 재귀적으로 정렬
*/
public List<Integer> mergeSort(List<Integer> inList) {
if (inList.size() <= 1) {
return inList;
}
int mid = inList.size() / 2;
List<Integer> left = new ArrayList<>(inList.subList(0, mid));
List<Integer> right = new ArrayList<>(inList.subList(mid, inList.size()));
return merge(mergeSort(left), mergeSort(right));
}
/**
* 정렬된 두 개의 리스트를 하나로 합침
*/
private List<Integer> merge(List<Integer> left, List<Integer> right) {
List<Integer> result = new ArrayList<>();
int i = 0, j = 0;
// 양쪽 리스트의 원소를 비교하여 작은 순서대로 결과 리스트에 추가
while (i < left.size() && j < right.size()) {
if (left.get(i).compareTo(right.get(j)) <= 0) {
result.add(left.get(i));
i++;
} else {
result.add(right.get(j));
j++;
}
}
// 남아있는 원소 처리 (왼쪽)
while (i < left.size()) {
result.add(left.get(i));
i++;
}
// 남아있는 원소 처리 (오른쪽)
while (j < right.size()) {
result.add(right.get(j));
j++;
}
return result;
}
}