逆序对/归并排序的应用

来源:互联网 发布:测试风扇转速软件 编辑:程序博客网 时间:2024/05/22 04:53

给定一个数组,a[0,.....n-1]。对于其中i<j,但是a[i]>a[j],则认为存在一个逆序对。

可以利用归并排序思想结题



#include<iostream>
using namespace std;


void MergeSort(int *a, int low, int high, int &count);
void Merge(int *a, int low, int mid, int high, int &count);
void Print(int *a, int size);


int main()
{
int a[]={23,3,2,6,8,5};
int size=sizeof(a)/sizeof(int);
int count=0;
MergeSort(a,0,size-1,count);  //归并排序
    Print(a,size);
cout<< count<<endl;
return 0;
}




void MergeSort(int *a, int low, int high, int &count)
{
   if(low>=high)
  return;
   int mid =(low+high)/2;
   MergeSort(a,low,mid,count);
   MergeSort(a,mid+1,high,count);
   Merge(a,low,mid,high,count);
}


int temp[100];
void Merge(int *a, int low, int mid, int high, int &count)
{
   int i=low;
   int j=mid+1;
   int size=0;
   for(;(i<=mid)&&(j<=high); size++)
   {
      if(a[i]<a[j])
 temp[size]=a[i++];
 else
 {
     count+=(mid-i+1);
 temp[size]=a[j++];
 }  
   }
   while(i<=mid)
  temp[size++]=a[i++];
    while(j<=high)
  temp[size++]=a[j++];
for(i=0;i<size;i++)
a[low+i]=temp[i];
}


 void Print(int *a, int size)
{
   for(int i=0; i<size;i++)
   cout<<*(a+i)<<" ";
   cout<<endl;
   
}

0 0
原创粉丝点击