제자리 정렬 inplace MergeSort, 공간 복잡 도 O (1)

3042 단어 cnullp2p
난이 도 는 현지에서 합 쳐 진다. 코드 와 주석 을 보라 고 한다.이전 문장 과 약간 유사 하 다.
//============================================================================
//@lgh  
//============================================================================

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
void pr_arr(char* first,char*last)
{
	while(first!=last)
	{
		printf("%c",*first++);
	}
}
void swap(char*s1,char*s2)
{
	if(*s1!=*s2)
	{
		char t=*s1;
		*s1=*s2;
		*s2=t;
	}
}
//         val     
char* lower_bound(char*first,char*last,int val)
{
	int len=last-first;
	while(len>0)
	{
		int half=len>>1;
		char*mid=first+half;
		if(*mid < val)
		{
			first=mid+1;
			len=len-half-1;
		}
		else
			len=half;
	}
	return first;
}
//       val      。
char* upper_bound(char*first,char*last,char val)
{
	int len=last-first;
	while(len>0)
	{
		int half=len>>1;
		char* mid=first+half;
		if(*mid<=val)
		{
			first=mid+1;
			len=len-half-1;
		}
		else{
			len=half;
		}
	}
	return first;
}
//     ,      
int gcd(int m,int n)
{
	while(n!=0)
	{
		int t=n;
		n=m%n;
		m=t;
	}
	return m;
}
//shift   ,  ==mid-begin
void rotate_recyle(char*begin,char*end,char*initial,int shift)
{
	char t=*initial;
	int len=end-begin;
	char *p1=initial; //p1     
	char *p2=p1+shift; //p2  p1         ,     p1+shift
	while(p2!=initial)
	{
		*p1=*p2;
		p1=p2;
		p2=begin+(p2-begin+shift)%len; //p2      ,     
	}
	*p1=t;
}
/*   p2=begin+(p2-begin+shift)%len     , STL
 if(end-p2>shift) p2+=shift;
 else p2=begin+(shift-(end-p2));
 */
void rotate(char*begin,char*mid,char*end) //      
{
	if(begin==mid || mid==end) return;
	int n=gcd(mid-begin,end-begin);
	while(n--)
	{
		rotate_recyle(begin,end,begin+n,mid-begin);
	}
}
/*  :    : [13579,2468]       
 *   1     ,      1    5,   [2468]        5   6
 *        :[13,579][24,68]   [579] > [24]     
 * [13,24]<=[579,68],     ,[13,24]、[579,68]        ,  OK
 *PS:  2   ,  。
*/
void inplaceMerge(char*first,char*mid,char*last)
{
	int len1=mid-first,len2=last-mid;
	if(0==len1 || 0==len2) return ;
	if(len1+len2==2)//      , 
	{
		if(*mid<*first) swap(first,mid);
		return;
	}
	char *firstCut, *secondCut;
	if(len1>len2) //  1>  2
	{
		firstCut=first+(len1>>1); //  1    
		secondCut=lower_bound(mid,last,*firstCut); //             
	}
	else
	{
		secondCut=mid+(len2>>1); //  2    
		firstCut=upper_bound(first,mid,*secondCut); //           
	}
	//      [firstCut,mid)>[mid,secondCut),     ,          。
	rotate(firstCut,mid,secondCut);
	char* newMid=firstCut+(secondCut-mid); //     
	inplaceMerge(first,firstCut,newMid);
	inplaceMerge(newMid,secondCut,last);
}
void inplaceMergeSort(char s[],int len)
{
	if(s==NULL || len<=1) return;
	inplaceMergeSort(s,len/2);
	inplaceMergeSort(s+len/2,len-len/2);
	inplaceMerge(s,s+len/2,s+len);
}
int main() {
	char s[] ="0124683579";
	int len = strlen(s);
	inplaceMergeSort(s,len);
	printf("%s 
", s); return 0; }

좋은 웹페이지 즐겨찾기