合并排序源代码
这是偷来的合并排序代码,2000W个整数大概10秒左右,我想问下问什么我把数组增加到1E排序完了会死机啊???
难道是偷来的东西就用不成???!!!
const DWORD size = 20000000;
int arry [ size ] ;
int _tmain(int argc, _TCHAR* argv[])
{
srand( GetTickCount( ) ) ;
for( DWORD i = 0 ; i<size ; i++)
arry[ i ] = rand( ) ;
DWORD lasttick = GetTickCount( ) ;
MergeSort( arry ,size ) ;
lasttick = GetTickCount( ) - lasttick ;
cout<<"Merge Sort times : "<<lasttick <<endl;
return 0;
}
template< class type >
void MergeSort( type * arry , int size ) ;
template< class type >
void Merge( type * p1 , type * p2 ) ;
template< class type >
void Merge( type * p1 , type * p2 , int size ) ;
template< class type >
void Merge( type * p1 , type * p2 )
{
#if _DEBUG
assert( p1 && p2 && p1 != p2 ) ;
#endif
int size = p2 - p1 ;
type * p1temp = p1 ;
type * p2temp = p2 ;
type * arry = new type[ size * 2 ] ;
type * parry = arry ;
#if _DEBUG
assert( arry ) ;
#else
if( !arry )
return ;
#endif
do
{
if( *p1temp <= *p2temp )
*parry ++ = *p1temp ++ ;
else
*parry ++ = *p2temp ++ ;
if( p1temp == p2 )
{
while( p2temp != p2 + size )
*parry ++ = *p2temp ++ ;
break ;
}
else if( p2temp == p2 + size )
{
while( p1temp != p2 )
*parry ++ = *p1temp ++ ;
break ;
}
}while( true ) ;
parry = arry ;
p1temp = p1 ;
do
{
*p1temp ++ = *parry ++ ;
}while( p1temp < p2 + size ) ;
delete [ ] arry ;
}
template< class type >
void Merge( type * p1 , type * p2 , int size )
{
#if _DEBUG
assert( p1 && p2 ) ;
#else
if( !p1 || !p2 )
return ;
#endif
int count = p2 - p1 ;
type * arry = new type[ count + size ] ;
#if _DEBUG
assert( arry ) ;
#else
if( !arry )
return ;
#endif
type * parry = arry ;
type * p1temp = p1 ;
type * p2temp = p2 ;
do
{
if( *p1temp <= *p2temp )
*parry ++ = *p1temp ++ ;
else
*parry ++ = *p2temp ++ ;
if( p1temp == p2 )
{
while( p2temp != p2 + size )
*parry ++ = *p2temp ++ ;
break ;
}
else if( p2temp == p2 + size )
{
while( p1temp != p2 )
*parry ++ = *p1temp ++ ;
break ;
}
}while( true ) ;
parry = arry ;
p1temp = p1 ;
do
{
*p1temp ++ = *parry ++ ;
}while( p1temp < p2 + size ) ;
delete [ ] arry ;
}
template< class type >
void MergeSort( type * arry , int size )
{
if( !arry || size <= 1 )
return ;
type * pend = arry + size ;
int i ;
for( i = 2 ; i <= size ; i *= 2 )
{
type * pbeg = arry ;
do
{
Merge( pbeg , pbeg + i / 2 ) ;
pbeg += i ;
}while( pbeg + i <= pend ) ;
if( pbeg == pend )
continue ;
else if( pbeg + i / 2 >= pend )
continue ;
else
Merge( pbeg , pbeg + i / 2 , pend - pbeg - i / 2 ) ;
}
if( i != size )
Merge( arry , arry + i / 2 , size - i / 2 ) ;
}