归并排序

#include <iostream>            //递归
using namespace std;
int n,list[200],temp[200];
void merge_sort(int beg,int end)
{
if(end==beg)
return ;
int mid=(beg+end)/2;
merge_sort(beg,mid);
merge_sort(mid
+1,end);
int p=beg,q=mid+1,t=beg;
while(p<=mid||q<=end)
{
if(q>end||(p<=mid&&list[p]<list[q]))
temp[t
++]=list[p++];
else
temp[t
++]=list[q++];
}
for(int i=beg;i<=end;++i)
{
list[i]
=temp[i];
}
}
int main()
{
cin
>>n;
for(int i=0;i<n;++i)
cin
>>list[i];
merge_sort(
0,n-1);
for(int i=0;i<n;++i)
cout
<<list[i]<<" ";
cout
<<endl;
return 0;
}

  

//POJ 2299 Ultra-QuickSort

#include <iostream> //求归并排序的逆序数
using namespace std;
__int64 list[
500005],temp[500005],amount;
int n;
void merge_sort(int beg,int end)
{
if(end==beg)
return ;
int mid=(beg+end)/2;
merge_sort(beg,mid);
merge_sort(mid
+1,end);
int p=beg,q=mid+1,t=beg;
while(p<=mid||q<=end)
{
if(q>end||(p<=mid&&list[p]<list[q]))
temp[t
++]=list[p++];
else
{
temp[t
++]=list[q++];
amount
+=mid-p+1;
}
}
for(int i=beg;i<=end;++i)
{
list[i]
=temp[i];
}
}
int main()
{
while(cin>>n&&n)
{
amount
=0;
for(int i=0;i<n;++i)
scanf(
"%I64d",&list[i]);
merge_sort(
0,n-1);
printf(
"%I64d\n",amount);
}
return 0;
}

  

posted on 2011-08-22 15:01  sysu_mjc  阅读(181)  评论(0编辑  收藏  举报

导航