归并排序详解(戳我)。
以下是搬了别人的。
代码语言:javascript复制#include<stdio.h>
#include<stdlib.h>
long long sum = 0;
int a[100005];
int temp[100005];
void Merge(int s1, int e1, int s2, int e2)
{
int p = 0;
int p1 = s1;
int p2 = s2;
while(p1 <= e1 && p2 <= e2)
{
if(a[p1] <= a[p2])
{
temp[p ] = a[p1 ];
}
else
{
temp[p ] = a[p2 ];
sum = (e1 - p1 1);
}
}
while(p1 <= e1)
{
temp[p ] = a[p1 ];
}
while(p2 <= e2)
{
temp[p ] = a[p2 ];
}
for(int i = s1; i <= e2; i )
{
a[i] = temp[i - s1];
}
}
void Merge_sort(int s, int e)
{
int m;
if(s < e)
{
m = ( s e ) / 2;
Merge_sort(s, m);
Merge_sort(m 1, e);
Merge(s, m , m 1, e);
}
}
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
for(int i = 0; i < n; i )
{
scanf("%d",&a[i]);
}
sum = 0;
Merge_sort(0,n-1);
printf("%lldn",sum);
}
return 0;
}