求数组中的逆序对
#include<iostream> using namespace std; int MergeArray(int r[],int s,int m,int e,int temp[]){ int i=m,j=e,count=0,k=0; while(i>=s&&j>=m+1){ if (r[i]>r[j]){ temp[k]=r[i]; k++; count=count+(j-m); i--; } else if (r[i]<=r[j]){ temp[k]=r[j]; k++; j--; } } while(i>=s)//表示前半段数组中还有元素未放入临时数组 { temp[k++]=r[i--]; } while(j>m) { temp[k++]=r[j--]; } for(int z=0;z<k;z++){ r[e-z]=temp[z]; } return count; } int Nixudui(int r[],int s,int e,int temp[]){ int count=0; if(s<e){//递归的界限 int m=(s+e)/2; count+=Nixudui(r,s,m,temp); count+=Nixudui(r,m+1,e,temp); count+=MergeArray(r,s,m,e,temp); } return count; } void main(){ int A[4]={7,5,6,4}; int *temp=new int[4]; int rs; rs=Nixudui(A,0,3,temp); delete[] temp; cout<<rs<<endl; system("pause"); }
时间: 2024-11-08 07:45:38