// InsertSort.c
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
typedef int DataType;
typedef char NumType; // 有效个数:2至127
// ( ( 2 ^ ( ( sizeof ( NumType ) * 8 ) - 1 ) - 1 )
#define LIMIT ( NumType ) ( ( 1 << ( ( sizeof ( NumType ) << 3 ) - 1 ) ) - 1 )
void InsertSort(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))
InsertSort(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 InsertSort(DataType * const data, const NumType sum)
{
#define FLAG 0 // FLAG = 0 升序排列 FLAG = 1 降序排列
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;
}
}