-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0912-sort-an-array.c
74 lines (52 loc) · 1.13 KB
/
0912-sort-an-array.c
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
void merge(int *array,int l,int m, int r){
int n1 = m-l+1;
int n2 = r-m;
int * left = (int *)malloc(sizeof(int)*n1);
int * right=(int *)malloc(sizeof(int)*n2);
for(int i=0;i<n1;i++){
left[i]=array[l+i];
}
for(int j=0;j<n2;j++){
right[j]=array[m+j+1];
}
int i=0;
int j=0;
int k=l;
while(i<n1 && j<n2){
if(left[i]<=right[j]){
array[k]=left[i];
i++;
}else{
array[k]=right[j];
j++;
}
k++;
}
while(i<n1){
array[k]=left[i];
i++;
k++;
}
while(j<n2){
array[k]=right[j];
j++;
k++;
}
}
void mergesort(int * array, int l,int r){
if(l<r){
int m = (l+r)/2;
mergesort(array,l,m);
mergesort(array,m+1,r);
merge(array,l,m,r);
}
}
int* sortArray(int* nums, int numsSize, int* returnSize) {
int *array = (int *) malloc(sizeof(int)*numsSize);
for(int i=0;i<numsSize;i++){
array[i]=nums[i];
}
mergesort(array,0,numsSize-1);
*returnSize=numsSize;
return array;
}