Last active
June 6, 2016 05:19
-
-
Save taznica/6ee9cf63b20b528e3a87cc87f4437ba4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
int merge(int data[], int p, int q, int r) | |
{ | |
int i, j, k; | |
int n1=q-p; | |
int n2=r-q; | |
int t; | |
int times=0; | |
int *L=(int *)malloc(sizeof(int)*n1); | |
int *R=(int *)malloc(sizeof(int)*n2); | |
if(L==NULL) | |
{ | |
puts("ERROR"); | |
return 1; | |
} | |
if(R==NULL) | |
{ | |
puts("ERROR"); | |
return 1; | |
} | |
for(t=0;t<n1;t++) | |
{ | |
L[t]=data[p+t]; | |
} | |
for(t=0;t<n2;t++) | |
{ | |
R[t]=data[q+t]; | |
} | |
i=0; | |
j=0; | |
k=p; | |
while(i<n1 && j<n2) | |
{ | |
if(L[i]<R[j]) | |
{ | |
data[k]=L[i]; | |
i+=1; | |
k+=1; | |
} | |
else | |
{ | |
data[k]=R[j]; | |
j+=1; | |
k+=1; | |
} | |
if(i<n1) | |
{ | |
for(t=i;t<n1;t++) | |
{ | |
data[k]=L[t]; | |
k+=1; | |
} | |
} | |
else | |
{ | |
for(t=j;t<n2;t++) | |
{ | |
data[k]=R[t]; | |
k+=1; | |
} | |
} | |
} | |
free(L); | |
free(R); | |
return times; | |
} | |
int mergeSort(int data[], int p, int r) | |
{ | |
int times=0; | |
if(p+1<r) | |
{ | |
int q; | |
q=(p+r)/2; | |
mergeSort(data, p, q); //p番目からq個目の配列 | |
mergeSort(data, q, r); | |
merge(data, p, q, r); | |
} | |
return times; | |
} | |
int main() | |
{ | |
int n, i; | |
scanf("%d", &n); | |
int *data=(int *)malloc(sizeof(int)*n); | |
if(data==NULL) | |
{ | |
puts("ERROR"); | |
return 1; | |
} | |
for(i=0;i<n;i++) | |
{ | |
scanf("%d", &data[i]); | |
} | |
mergeSort(data, 0, n); | |
for(i=0;i<n;i++) | |
{ | |
printf("%d ", data[i]); | |
} | |
printf("%d\n", data[n-1]); | |
free(data); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment