-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge_sort.cpp
More file actions
81 lines (63 loc) · 969 Bytes
/
Copy pathmerge_sort.cpp
File metadata and controls
81 lines (63 loc) · 969 Bytes
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
70
71
72
73
74
75
76
77
78
79
80
81
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
void merge(vector<int> &a,int l,int r,int mid)
{
int i,j,k;//辅助数组
vector<int> aux;
for(k=l;k<=r;k++)
aux.push_back(a[k]);//把这一部分截下来
i=l;
j=mid+1;
for(k=l;k<=r;k++)
{
if(i>mid)
{
a[k]=aux[j-l];
j++;
}
else if(j>r)
{
a[k]=aux[i-l];
i++;
}
else if(aux[i-l]>aux[j-l])
{
a[k]=aux[j-l];
j++;
}
else if(aux[i-l]<=aux[j-l])
{
a[k]=aux[i-l];
i++;
}
}
}
void merge_sort(vector<int> &a,int l,int r)
{
if(l>=r){
return;
}
int mid=(l+r)/2;
merge_sort(a,l,mid);
merge_sort(a,mid+1,r);
merge(a,l,r,mid);
}
int main()
{
int n,i;
scanf("%d",&n);
vector<int> a;
for(i=0;i<n;i++){
int tmp;
cin>>tmp;
a.push_back(tmp);
}
merge_sort(a,0,n-1);//调用归并排序代码
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}