归并问题可以解决有多个逆序对和最小和问题。
下面证明其时间复杂度:
对N个数归并排序的用时等于对两个大小为N/2的递归排序所用的时间再加上合并的时间:
T(N)=2T(N/2)+N
两边同时除N T(N)/N=T(N/2)/(N/2)+1;
T(N/2)/(N/2)= T(N/4)/(N/4)+1;
.
.
.
T(N)/N=T(1)/1+logN;
所以时间复杂度为 T(N)=NlogN+N=O(NlogN)
若要想求逆序对,则用center-righ+1,因为左边已是依次增大排好序的
#include<bits/stdc++.h>
using namespace std;
void Merge(int a[],int temparray[],int lpos,int rpos,int rightend);
void Mergesort(int a[],int temparray[],int left,int right){
if(left<right)
{
int center=(right+left)/2;
Mergesort(a,temparray,left,center);
Mergesort(a,temparray,center+1,right);
Merge(a,temparray,left,center+1,right);
}
}
void Merge(int a[],int temparray[],int lpos,int rpos,int rightend){
int leftend=rpos-1;
int num=rightend-lpos+1;
int tempos=lpos;
while(lpos<=leftend && rpos<=rightend)
if(a[lpos]<=a[rpos])
temparray[tempos++]=a[lpos++];
else
temparray[tempos++]=a[rpos++];
while(lpos<=leftend)
temparray[tempos++]=a[lpos++];
while(rpos<=rightend)
temparray[tempos++]=a[rpos++];
for(int i=0;i<num;i++,rightend--)
a[rightend]=temparray[rightend];
}
int main()
{
int a[]={23,46,0,8,11,18};
int* temparray=(int *)malloc(sizeof(int)*(sizeof(a)/sizeof(a[0])));
Mergesort(a,temparray,0,sizeof(a)/sizeof(a[0])-1);
free(temparray);
for(int i=0;i<6;i++)
printf("%d ",a[i]);
}
排序(5)----归并排序及证明其时间复杂度O(Nlog^N)
最新推荐文章于 2024-06-19 11:21:00 发布