排序(5)----归并排序及证明其时间复杂度O(Nlog^N)

归并问题可以解决有多个逆序对和最小和问题。
下面证明其时间复杂度:
对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]);

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值