// QuickSort with recursion.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SWAP(x,y,t) ((t) = (x), (x) = (y), (y) = (t))
typedef int DataType;
typedef char NumType; // 有效个数:2至127
// ( ( 2 ^ ( ( sizeof ( NumType ) * 8 ) - 1 ) - 1 )
#define LIMIT ( NumType ) ( ( 1 << ( ( sizeof ( NumType ) << 3 ) - 1 ) ) - 1 )
DataType median3(DataType * const, const NumType, const NumType);
void quickS(DataType * const, const NumType, const NumType);
void InsertSort(DataType * const, const NumType);
void QuickSort(DataType * const, const NumType);
int main(void)
{
NumType i, sum;
DataType data[LIMIT] = { 0 };
srand((unsigned int)time(0));
puts("生成随机数:\n");
for (i = 0; i < LIMIT; ++i)
{
// 随机生成0至32767共计32768种随机数字
data[i] = rand();
printf("%-5d\t", data[i]);
if (i % 10 == 9)
putchar('\n');
}
sum = sizeof (data) / sizeof (data[0]);
// 数据个数溢出检测
if ((sizeof (sum) <= sizeof (NumType)) && (sum <= LIMIT) && (sum > 1))
QuickSort(data, sum);
puts("\n\n递归快速排序后:\n");
for (i = 0; i < LIMIT; ++i)
{
printf("%-5d\t", data[i]);
if (i % 10 == 9)
putchar('\n');
}
putchar('\n');
getch();
return 0;
}
/******************************以上代码仅供测试******************************/
// 递归快速排序
void swap(DataType * const x, DataType * const y)
{
DataType temp = *x;
*x = *y;
*y = temp;
}
DataType median3(DataType * const data, const NumType left, const NumType right)
{
DataType temp;
// NumType center = (left + right) / 2;
NumType center = (left + right) >> 1;
if (data[center] < data[left])
SWAP(data[left], data[center], temp);
if (data[right] < data[left])
SWAP(data[left], data[right], temp);
if (data[right] < data[center])
SWAP(data[right], data[center], temp);
SWAP(data[center], data[right], temp);
return data[right];
}
void quickS(DataType * const data, const NumType left, const NumType right)
{
#define FLAG 1 // FLAG = 0 升序排列 FLAG = 1 降序排列
NumType i, j;
DataType temp, pivot;
if (left + 10 <= right)
{
pivot = median3(data, left, right);
i = left;
j = right - 1;
for (; i < j;)
{
#if !FLAG // FLAG == 0
while (data[i] < pivot)
#elif FLAG // FLAG == 1
while (data[i] > pivot)
#endif
++i;
#if !FLAG // FLAG == 0
while (pivot < data[j])
#elif FLAG // FLAG == 1
while (pivot > data[j])
#endif
--j;
if (i < j)
{
SWAP(data[i], data[j], temp);
++i;
--j;
}
}
#if !FLAG // FLAG == 0
if ((i == j) && (data[i] < pivot))
#elif FLAG // FLAG == 1
if ((i == j) && (data[i] > pivot))
#endif
++i;
SWAP(data[i], data[right], temp);
quickS(data, left, i - 1);
quickS(data, i + 1, right);
}
else
InsertSort(data + left, right - left + 1);
}
void InsertSort(DataType * const data, const NumType sum)
{
DataType temp;
NumType i, j;
for (i = 1; i < sum; ++i)
{
temp = data[i];
#if !FLAG // FLAG == 0
for (j = i - 1; data[j] > temp && j >= 0; --j)
#elif FLAG // FLAG == 1
for (j = i - 1; data[j] < temp && j >= 0; --j)
#endif
data[j + 1] = data[j];
data[j + 1] = temp;
}
}
// 快速排序主函数
void QuickSort(DataType * const data, const NumType sum)
{
quickS(data, 0, sum - 1);
}