快速排序算法代码
# include <iostream>
using namespace std;
typedef int ElementType;
void Swap ( int * a, int * b) {
int temp = * a;
* a = * b;
* b = temp;
}
void Insertion_sort ( int A[ ] , int N) {
for ( int p = 1 ; p < N; p++ ) {
int tmp = A[ p] ;
int j = p;
for ( ; tmp < A[ j - 1 ] && j > 0 ; j-- )
A[ j] = A[ j - 1 ] ;
A[ j] = tmp;
}
}
ElementType Median3 ( ElementType A[ ] , int Left, int Right)
{
int Center = ( Left + Right) / 2 ;
if ( A[ Left] > A[ Center] )
Swap ( & A[ Left] , & A[ Center] ) ;
if ( A[ Left] > A[ Right] )
Swap ( & A[ Left] , & A[ Right] ) ;
if ( A[ Center] > A[ Right] )
Swap ( & A[ Center] , & A[ Right] ) ;
Swap ( & A[ Center] , & A[ Right - 1 ] ) ;
return A[ Right - 1 ] ;
}
void Qsort ( ElementType A[ ] , int Left, int Right)
{
int Pivot, Low, High;
if ( 2 < Right - Left) {
Pivot = Median3 ( A, Left, Right) ;
cout << Pivot << endl;
for ( int i = 0 ; i < 12 ; i++ )
cout << A[ i] << ' ' ;
cout << endl;
Low = Left; High = Right - 1 ;
while ( 1 ) {
while ( A[ ++ Low] < Pivot) ;
while ( A[ -- High] > Pivot) ;
if ( Low < High) Swap ( & A[ Low] , & A[ High] ) ;
else break ;
}
cout << "Low=" << Low << " High=" << High << endl;
Swap ( & A[ Low] , & A[ Right - 1 ] ) ;
Qsort ( A, Left, Low - 1 ) ;
Qsort ( A, Low + 1 , Right) ;
}
else
Insertion_sort ( A, Right - Left + 1 ) ;
}
void QuickSort ( ElementType A[ ] , int N)
{
Qsort ( A, 0 , N - 1 ) ;
}
int main ( )
{
int num[ 12 ] = { 23 , 45 , 17 , 11 , 13 , 89 , 72 , 26 , 3 , 17 , 11 , 13 } ;
int n = 12 ;
QuickSort ( num, n) ;
cout << "排序后的数组为:" << endl;
for ( int i = 0 ; i < n; i++ )
cout << num[ i] << ' ' ;
cout << endl;
return 0 ;
}