题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
归并排序思想:
#include "iostream"
using namespace std;
int static count =0;
//归并排序的思想
void mergearray(int* array,int first,int mid,int last)
{
int temp[10];
int m =mid,n =last,k=0;
int i=first,j=mid+1;
while (i<=m&&j<=n)
{
if (array[i]<array[j])
{
temp[k++] =array[i++];
}
else
{
temp[k++] =array[j++];
count +=m-i+1;
}
}
while (i<=m)
{
temp[k++] =array[i++];
}
while(j<=n)
{
temp[k++] =array[j++];
}
for (i=0;i<k;i++)
{
array[first+i] =temp[i];
}
}
void mergesort(int* array,int start,int end)
{
if (start>=end)
{
return;
}
int mid =(start+end)/2;
mergesort(array,start,mid);
mergesort(array,mid+1,end);
mergearray(array,start,mid,end);
}
void main()
{
int array[10] ={7,5,6,4};
mergesort(array,0,3);
for (int i=0;i<=3;i++)
{
cout<<array[i]<<" ";
}
cout<<endl;
cout<<"逆序数为:"<<count<<endl;
}