先对序列一个乱序值进行插入排序
int a[10] = { 1, 2, 3, 4, 6, 7, 8, 9, 10, 5 };//将5插入 从后往前与5比较 将大的排到后面
int temp = a[9];
int j = 9;//存储下标
while (j > 0 && a[j - 1] > temp)//a[j - 1] > temp 循环终止的条件 确定要插入的位置
{
a[j] = a[j - 1];//向前移动
j--;//下标做相应改变
for (int i = 0; i < 10; i++)//显示分步结果
{
printf("%d ", a[i]);
}
printf("\n");
}
a[j] = temp;//插入
for (int i = 0; i < 10; i++)//显示结果
{
printf("%d ", a[i]);
}
printf("\n");
getchar();
再对全乱序序列进行排序
void main()
{
int a[10] = { 1, 5, 2, 4, 3, 8, 7, 9, 10, 6 };
for (int i = 0; i < 10; i++)//i=0 只有一个数不需要插入
{
int temp = a[i];
int j = i;
while (j > 0 && a[j - 1] > temp)
{
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}
for (int i = 0; i < 10; i++)//显示结果
{
printf("%d ", a[i]);
}
printf("\n");
system("pause");
}