const int LENGTH=100;
int temp[LENGTH]; //额外的辅助数组
int count=0;
void Merge(int * array,int first,int med,int last)
{
int i=first,j=med+1;
int cur=0;
while (i<=med&&j<=last)
{
if (array[i]<array[j])
{
temp[cur++]=array[i++];
}
else
{
temp[cur++]=array[j++];
<span style="color:#ff0000;">count+=med-i+1</span>; //核心代码,逆序数增加
}
}
while (i<=med)
{
temp[cur++]=array[i++];
}
while (j<=last)
{
temp[cur++]=array[j++];
}
for (int m=0;m<cur;m++)
{
array[first++]=temp[m++];
}
}
void MergeSort(int *array,int first,int last)
{
if (first==last)
{
return ;
}
int med=first+(last-first)/2;
MergeSort(array,first,med);
MergeSort(array,med+1,last);
Merge(array,first,med,last);
}
O(nlogn)实现逆序数求值
最新推荐文章于 2020-05-20 09:32:48 发布