#include<iostream>
using namespace std;
#define MAXSIZE 21
typedef int SqList[MAXSIZE];
#define ElementType int
void Swap(int &a, int &b)
{
a = a^b;
b = a^b;
a = a^b;
}
//*********************************************************
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 ] );
return A[ Right ]; /* 返回pivot */
}
void Quicksort( ElementType *A, int Left, int Right )
{
if(Left>=Right){return ;}
{
int Pivot = Median3( A, Left, Right );
int i = Left;
int j = Right;
for( ; ; )
{
while ( i<j && A[i] < Pivot ) { ++i; }
// 注意这里是>=否则当Pivot和头尾数据相等时就会死循环
while ( i<j && A[j] >= Pivot ) { --j; }
if ( i < j )
Swap( A[i], A[j] );
else break;
}
Swap( A[i], A[Right] );
Quicksort( A, Left, i-1 );
Quicksort( A, i+1, Right );
}
}
void Quick_Sort(ElementType *A,int N)//接口
{
Quicksort( A, 0, N-1 );
}
//
void main()
{
SqList sq = {49,38, 65, 97, 76, 13, 27, 49 };
Quick_Sort( sq,8);//
for (int i = 0; i < 8; i++)
{
cout << sq[i] <<",";
}
cout << endl;
}
为了尽可能降低复杂度,出现了一些边界控制的问题,在老师的帮助下,完成了代码。
有不足之处,还望指出。