归并排序的递归实现
class MergeSort {
public:
int * mergeSort ( int * A, int n) {
merge ( A, 0 , n- 1 ) ;
return A;
}
void merge ( int * A, int left, int right)
{
if ( left< right)
{
int middle= ( left+ right) / 2 ;
merge ( A, left, middle) ;
merge ( A, middle+ 1 , right) ;
mergearray ( A, left, middle, right) ;
}
}
void mergearray ( int * A, int left, int m, int right)
{
int tmpA[ right- left+ 1 ] ;
int i= left, j= m+ 1 , tmpi= 0 ;
while ( i<= m&& j<= right)
{
if ( A[ i] <= A[ j] )
tmpA[ tmpi++ ] = A[ i++ ] ;
else
tmpA[ tmpi++ ] = A[ j++ ] ;
}
while ( i<= m)
tmpA[ tmpi++ ] = A[ i++ ] ;
while ( j<= right)
tmpA[ tmpi++ ] = A[ j++ ] ;
for ( tmpi= 0 ; tmpi< right- left+ 1 ; tmpi++ )
A[ left+ tmpi] = tmpA[ tmpi] ;
}
} ;
快速排序递归实现
class QuickSort {
public:
int * quickSort ( int * A, int n) {
quicksort ( A, 0 , n- 1 ) ;
return A;
}
void quicksort ( int * A, int left, int right)
{
if ( left< right)
{
int pvoit= partition ( A, left, right) ;
quicksort ( A, left, pvoit- 1 ) ;
quicksort ( A, pvoit+ 1 , right) ;
}
}
int partition ( int * A, int left, int right)
{
int pvoitkey= A[ left] ;
while ( left< right) {
while ( left< right&& A[ right] >= pvoitkey) right-- ;
swap ( A[ left] , A[ right] ) ;
while ( left< right&& A[ left] <= pvoitkey) left++ ;
swap ( A[ left] , A[ right] ) ;
}
return left;
}
} ;