-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge sort
58 lines (53 loc) · 1.15 KB
/
merge sort
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
//
// main.c
// mergesort
//
// Created by 毛遵杰 on 2019/12/11.
// Copyright © 2019 毛遵杰. All rights reserved.
//
typedef int ElemType;
void print(int a[], int n){
for(int j= 0; j<n; j++){
printf("a[j]\n");
}
printf("\n");
}
void Merge(ElemType *r,ElemType *rf, int i, int m, int n)
{
int j,k;
for(j=m+1,k=i; i<=m && j <=n ; ++k){
if(r[j] < r[i]) rf[k] = r[j++];
else rf[k] = r[i++];
}
while(i <= m) rf[k++] = r[i++];
while(j <= n) rf[k++] = r[j++];
print(rf,n+1);
}
void MergeSort(ElemType *r, ElemType *rf, int lenght)
{
int len = 1;
ElemType *q = r ;
ElemType *tmp ;
while(len < lenght) {
int s = len;
len = 2 * s ;
int i = 0;
while(i+ len <lenght){
Merge(q, rf, i, i+ s-1, i+ len-1 );
i = i+ len;
}
if(i + s < lenght){
Merge(q, rf, i, i+ s -1, lenght -1);
}
tmp = q; q = rf; rf = tmp;
}
}
int main(){
int a[10] = {12,2,16,30,28,10,16,20,6,18};
int b[10];
MergeSort(a, b, 10);
print(b,10);
printf("result:");
print(a,10);
return 0;
}