퀵소트보다 더 쉬운 합병정렬
설명은 집가서 달게유
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
|
#include <iostream>
#include <stdio.h>
#define MAX 100
void merge(int* arr, int left, int right) {
int temp[MAX];
int mid = (left + right) / 2;
int i = left, j = mid + 1;
int idx = 0;
while (i <= mid && j <= right) {
if (arr[i] < arr[j]) temp[idx++] = arr[i++];
else temp[idx++] = arr[j++];
}
// 남은거
while (i <= mid) {
temp[idx++] = arr[i++];
}
while (j <= right) {
temp[idx++] = arr[j++];
}
idx = 0;
for (int i = left; i <= right; i++) {
arr[i] = temp[idx++];
}
}
void merge_sort(int* arr, int left, int right) {
if (left < right) {
// divide
int mid = (left + right) / 2;
merge_sort(arr, left, mid);
merge_sort(arr, mid + 1, right);
// conquer
merge(arr, left, right);
}
}
int main() {
int arr[] = { 6,1,2,9,3,7,4 };
merge_sort(arr, 0, 6);
for (int i = 0; i < 7; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
|
cs |