归并排序

Posted by Chenyawei on 2019-12-05
Words 310 and Reading Time 1 Minutes
Viewed Times

二路归并排序思路:

将原始序列看作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
#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 100;

/**
* 将数组A的[L1,R1]与[L2,R2]区间合并为有序的区间
* */
void merge(int A[], int L1, int R1, int L2, int R2){
int i=L1, j=L2;
int temp[maxn], index = 0;
while(i < R1 && j < R2){
if(A[i] <= A[j]){
temp[index++] = A[i++];
}else{
temp[index++] = A[j++];
}
}
while (i < R1) temp[index++] = A[i++];
while (j < R2) temp[index++] = A[j++];
for(i = 0; i < index; i++){
A[L1 + 1] = temp[i];
}
}

/**
* 2路归并归并排序: 递归实现
* */
void mergeSort(int A[], int left, int right){
if(left < right){
int mid = (left + right) / 2;
mergeSort(A, left, mid);
mergeSort(A, mid+1, right);
merge(A, left, mid, mid + 1, right);
}
}

int n;
/**
* 2路归并归并排序:非递归实现
* */
void mergeSort(int A[]){
for(int step = 2; step / 2 <= n; step *= 2){
for(int i = 1; i <= n; i += step){
int mid = i + step / 2 -1;
if(mid + 1 <= n){
merge(A, i, mid, mid + 1, min(i + step - 1,n));
}
}
}
}

notice

欢迎访问 chenyawei 的博客, 若有问题或者有好的建议欢迎留言,笔者看到之后会及时回复。 评论点赞需要github账号登录,如果没有账号的话请点击 github 注册, 谢谢 !

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !