[자료구조] MeargeSort(병합 정렬) - Java

1. 병합정렬(MeargeSort)

1.1 병합 정렬이란?

  1. 정렬할때 가장 작은 단위로 나눠서 정렬후(sort) 병합(mearge)하는 것을 말한다.

문제.2751 [백준] 수 정렬하기 2

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
57
58
59
60
61
62
63
64
65
66
67
68
69


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

public static void mergeSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
}

public static void mergeSort(int[] arr, int start, int end) {

int[] tmp = new int[arr.length];
if (start < end) {
int mid = (start + end) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
mearge(arr, start, mid, end);
}

}

private static void mearge(int[] arr, int start, int mid, int end) {
int[] tmp = new int[arr.length];
for (int i = start; i <= end; i++) {
tmp[i] = arr[i];
}
int part1 = start;
int part2 = mid + 1;
int index = start;
while (part1 <= mid && part2 <= end) {
if (tmp[part1] <= tmp[part2]) {
arr[index] = tmp[part1];
part1++;
} else {
arr[index] = tmp[part2];
part2++;
}
index++;
}

for (int i = 0; i <= mid - part1; i++) {
arr[index + i] = tmp[part1 + i];
}

}

private static void printArray(int[] arr) {
for (int i : arr) {
System.out.println(i);
}

}

public static void main(String[] args) throws NumberFormatException, IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
br.close();
mergeSort(arr);
printArray(arr);
}
}
  • 4,3,2,1 배열을 정렬할때 아래 순으로 졍렬된다.
4 3 2 1
3 4 2 1
3 4 1 2
1 2 3 4

댓글

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×