#include<stdio.h>
#include<stdlib.h>
void insertSort(int a[], int n) //从小到大排序
{
int insertVal, insertIndex;
for (int i = 1; i < n; i++)
{
insertVal = a[i];
insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < a[insertIndex])
{
a[insertIndex + 1] = a[insertIndex];
insertIndex--;
}
a[insertIndex + 1] = insertVal;
}
}
void printA(int a[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%3d", a[i]);
}
printf("\n");
}
int main()
{
int a[NUM];
srand(time(0));
for (int i = 0; i < NUM; i++)
{
a[i] = rand() % 99 + 1;
}
printf("原始数据:\n");
printA(a, NUM);
insertSort(a, NUM);
printf("插入排序后的数据:\n");
printA(a, NUM);
system("pause");
return 0;
#include<stdlib.h>
#include<time.h>
void insertSort(int a[], int n) //从小到大排序
{
int insertVal, insertIndex;
for (int i = 1; i < n; i++)
{
insertVal = a[i];
insertIndex = i - 1;
while (insertIndex >= 0 && insertVal < a[insertIndex])
{
a[insertIndex + 1] = a[insertIndex];
insertIndex--;
}
a[insertIndex + 1] = insertVal;
}
}
void printA(int a[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%3d", a[i]);
}
printf("\n");
}
int main()
{
int a[NUM];
srand(time(0));
for (int i = 0; i < NUM; i++)
{
a[i] = rand() % 99 + 1;
}
printf("原始数据:\n");
printA(a, NUM);
insertSort(a, NUM);
printf("插入排序后的数据:\n");
printA(a, NUM);
system("pause");
return 0;
}
运行结果: