快速排序算法的原理:
将数列中任取一个数,将其左部放置比其小的数,其右部放置比其大的数。然后,对其左,右部递归执行这种分割过程。
源码如下:
INT32 SortedData[] = { 1, 3, 2, 112, 3854, 2382, 28392,1283,483,839,7, 1838,18289,9, 848,8, 7, 18, 1, 38392, 192938493, 81928374, 48393291, 3848392, 44849332, 2847598, 0x18293, 2839482, 17829398, 71891238, 882929, 18, 2, 8392918, 2839281, 1839238, 9182839, 3849828, 1829381, 3829183, 28392, 3829482 };
INT32 QuickSort( INT32 *SortData, DWORD SortDataLen )
{
#define SEL_DATA_INDEX 0
INT32 i;
INT32 j;
INT32 Sel_Data;
INT32 *LeftSortData;
INT32 *RightSortData;
DWORD LeftDataLen;
DWORD RightDataLen;
INT32 Count;
LeftSortData = ( INT32* )malloc( SortDataLen * sizeof( INT32 ) );
RightSortData = ( INT32* )malloc( SortDataLen * sizeof( INT32 ) );
if( LeftSortData == NULL || RightSortData == NULL )
{
return -E_OUTOFMEMORY;
}
ASSERT( SortData != NULL );
ASSERT( SortDataLen > 0 );
LeftDataLen = 0;
RightDataLen = 0;
Sel_Data = SortData[ SEL_DATA_INDEX ];
for( i = 1; i < SortDataLen; i ++ )
{
if( SortData[ i ] <= Sel_Data )
{
LeftSortData[ LeftDataLen ++ ] = SortData[ i ];
}
else if( SortData[ i ] > Sel_Data )
{
RightSortData[ RightDataLen ++ ] = SortData[ i ];
}
}
#define MIN_SORT_DATA_LEN 1
if( LeftDataLen > MIN_SORT_DATA_LEN )
{
QuickSort( LeftSortData, LeftDataLen );
}
if( RightDataLen > MIN_SORT_DATA_LEN )
{
QuickSort( RightSortData, RightDataLen );
}
Count = 0;
for( i = 0; i < LeftDataLen; i ++ )
{
SortData[ Count ++ ] = LeftSortData[ i ];
}
SortData[ Count ++ ] = Sel_Data;
for( i = 0; i < RightDataLen; i ++ )
{
SortData[ Count ++ ] = RightSortData[ i ];
}
free( LeftSortData );
free( RightSortData );
return 0;
}
void main()
{
QuickSort( SortedData, sizeof( SortedData ) / sizeof( SortedData[ 0 ] ) );
}
程序中使用第1个元素做为先择元素。