插入排序算法

来源:互联网 发布:python 爬虫工作原理 编辑:程序博客网 时间:2024/05/17 09:12

// 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 == 0for (j = i - 1; data[j] > temp && j >= 0; --j)#elif FLAG // FLAG == 1for (j = i - 1; data[j] < temp && j >= 0; --j)#endifdata[j + 1] = data[j];data[j + 1] = temp;}}


0 0