C语言归并排序

C语言归并排序

van 知其变,守其恒,为天下式.

归并排序是一种分治法的排序算法,它将数组分成两个子数组,分别排序后再合并。其时间复杂度为O(n log n),适合处理大规模数据的排序。

图解递归过程以及复杂度

归并排序过程分析

归并排序复杂度分析

代码实现

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
#include <stdio.h>

#define SIZE(a) (sizeof(a)/sizeof(a[0]))
#define N 7

void print_array(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

void merge_sort(int arrp[], int n);
int main(void) {

int arr[N] = { 38,27,43,3,9,82,10 };
print_array(arr, N);
merge_sort(arr,N);

return 0;
}
int tmp[N];
void merge(int arr[], int left, int mid, int right) {
int i = left, j = mid + 1, k = left;
while (i <= mid && j <= right)
{
if (arr[i] <= arr[j])
{
tmp[k++] = arr[i++];
}
else
{
tmp[k++] = arr[j++];
}
}
while (i <= mid)
{
tmp[k++] = arr[i++];
}
while (j <= right)
{
tmp[k++] = arr[j++];
}
for (int k = left; k <= right; k++) {
arr[k] = tmp[k];
}
}
void m_sort(int arr[], int left, int right) {
if (left >= right)
{
return;
}
int mid = left + (right - left >> 1);
m_sort(arr, left, mid);
m_sort(arr, mid + 1, right);
merge(arr, left,mid, right);

print_array(arr, N);
}

void merge_sort(int arr[], int n) {
m_sort(arr, 0, n - 1);
}

代码运行结果

初始数组为:

1
38 27 43 3 9 82 10

排序过程中的数组变化:

1
2
3
4
5
6
7
38 27 43 3 9 82 10
27 38 43 3 9 82 10
27 38 3 43 9 82 10
3 27 38 43 9 82 10
3 27 38 43 9 82 10
3 27 38 43 9 10 82
3 9 10 27 38 43 82
  • Title: C语言归并排序
  • Author: van
  • Created at : 2024-05-22 00:30:07
  • Updated at : 2024-09-02 00:02:46
  • Link: https://xblog.aptzone.cc/2024/05/22/C语言归并排序/
  • License: All Rights Reserved © van
Comments