归并排序

划分 递归 合并

归并排序应用:解决逆序对问题

归并排序的实现

void mergearray(int a[],int first,int last,int b[])
{
    int mid=(first+last)/2;//将数组分为前后两部分 
    int i=first,j=mid+1;
    int num=0;
    int m=mid,n=last;
    while(i<=m&&j<=n)//在前后进行比较,较小的存放在b数组里 
    {
        if(a[i]<a[j])
            b[num++]=a[i++];//从左半数组复制到临时空间
        else
        {
            b[num++]=a[j++];//从右半数组复制到临时空间
        }
    }
    while(i<=m)//后面的数都比较完,i<m则将前面的数放入b 
    {
        b[num++]=a[i++];
    }
    while(j<=n)
    {
        b[num++]=a[j++];
    }
    for(int i=0;i<num;i++)//从辅助空间复制回到a数组
    {
        a[i]=b[i];
    }
}

求逆序对时间复杂度为nlog(n)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

int count;
void mergearray(int a[],int first,int mid,int last,int b[])
{
    int i=first,j=mid+1;
    int num=0;
    int m=mid,n=last;
    while(i<=m&&j<=n)
    {
        if(a[i]<a[j])
            b[num++]=a[i++];
        else
        {
            b[num++]=a[j++];
            count+=m-i+1;//如果后半数组的数小则说明前半数组的数均大于它
            //一共有m-i+1个数 
        }
    }
    while(i<=m)
    {
        b[num++]=a[i++];
    }
    while(j<=n)
    {
        b[num++]=a[j++];
    }
    for(int i=0;i<num;i++)
    {
        a[first+i]=b[i];//first开始递归不是从0开始 
    }
}
void mergesort(int a[],int first,int last,int b[])//递归求解 
{
    if(first<last)
    {
        int mid=(first+last)/2;
        mergesort(a,first,mid,b);
        mergesort(a,mid+1,last,b);
        mergearray(a,first,mid,last,b);
    }
 } 
bool mergesort(int a[],int n)
{
    int *p=new int[n];
    if(p==NULL)
        return false;
    mergesort(a,0,n-1,p);
        return true;
}
  
  
int main()  
{  
    int n,a[1000];
    cin>>n;
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    count = 0;  
    mergesort(a, n);  
    for(int i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    printf("逆序数对为: %d
", count);  
    return 0;  
}  
原文地址:https://www.cnblogs.com/renwjing/p/7388966.html