한쪽의 배열의 끝에 먼저 도달했을때 처리를 처음에 빼먹었다가 추가했다. Merge함수는 사실 생각하기 쉽고
MergeSort함수가 생각하기 어렵다.
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
|
int* Merge(int * left_array, int left_size, int * right_array, int right_size)
{
int left_index = 0;
int right_index = 0;
int merged_index = 0;
int* merged_array = (int*)malloc(sizeof(int)*(left_size + right_size));
while (merged_index < left_size + right_size)
{
if (right_index >= right_size)
{
merged_array[merged_index] = left_array[left_index];
left_index++;
//right_index = right_size - 1;
}
else if (left_index >= left_size)
{
merged_array[merged_index] = right_array[right_index];
right_index++;
// left_index = left_size - 1;
}
else
{
if (left_array[left_index] <= right_array[right_index])
{
merged_array[merged_index] = left_array[left_index];
left_index++;
}
else if (left_array[left_index] > right_array[right_index])
{
merged_array[merged_index] = right_array[right_index];
right_index++;
}
else
{
cout << "error" << endl;
}
}
merged_index++;
}
return merged_array;
}
|
재귀함수를 쓸때 재귀함수가 종료되는 조건을 항상 먼저 생각해두자.
병합정렬은 분할정복의 대표적인 예다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
int* MergeSort(int * inputArray, int size)
{
if (size <= 1)
{
return inputArray;
}
int* left= NULL;
int* right = NULL;
int mid = size / 2;
left = MergeSort(&inputArray[0], mid);
right = MergeSort(&inputArray[mid], size - mid);
return Merge(left, mid, right, size - mid);
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
'프로그래밍 > [Algorithm]' 카테고리의 다른 글
[Algorithm] DP-2 동적 테이블을 작성하는 Knapsack 예제풀이이다. (0) | 2020.06.01 |
---|---|
[Algorithm] 다익스트라 알고리즘 (0) | 2020.05.07 |
[Algorithm]그래프 입력받기 (0) | 2020.05.06 |
[Algorithm] dynamic programming-1 rod(막대기)문제 (0) | 2020.04.28 |
[Algorithm] dfs 간단 구현 (단지 번호 문제) (0) | 2020.04.27 |