// BubbleSort.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 unsigned char NumType; // 有效个数:2至255
// ( ( 2 ^ ( sizeof ( NumType ) * 8 ) ) - 1 )
#define LIMIT ( NumType ) ( ( 1 << ( sizeof ( NumType ) << 3 ) ) - 1 )
void BubbleSort(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))
BubbleSort(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 BubbleSort(DataType * const data, const NumType sum)
{
#define FLAG 1 // FLAG = 0 升序排列 FLAG = 1 降序排列
DataType temp;
NumType i, j, record = 0;
while (record < sum - 1)
{
j = sum - 1;
for (i = sum - 1; i > record; --i)
#if !FLAG // FLAG == 0
if (data[i - 1] > data[i])
#elif FLAG // FLAG == 1
if (data[i - 1] < data[i])
#endif
{
SWAP(data[i], data[i - 1], temp);
j = i;
}
record = j;
}
}