1. 编程学习网 > 编程教程 > C语言教程 > C语言经典案例:有一个已经排好序的数组。现输入一个数,要求按

C语言经典案例:有一个已经排好序的数组。现输入一个数,要求按

C语言案例分析:首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。

实现代码如下:

#include<stdio.h>

int main()

{

int a[11]={1,4,6,9,13,16,19,28,40,100};

int temp1,temp2,number,end,i,j;

printf("原始数组是:\n");

for(i=0;i<10;i++)

printf("%4d",a[i]);

printf("\n插入一个新的数字: ");

scanf("%d",&number);

end=a[9];

if(number>end)

a[10]=number;

else

{

for(i=0;i<10;i++)

{

if(a[i]>number)

{

temp1=a[i];

a[i]=number;

for(j=i+1;j<11;j++)

{

temp2=a[j];

a[j]=temp1;

temp1=temp2;

}

break;

}

}

}

for(i=0;i<11;i++)

printf("%4d",a[i]);

printf("\n");

return 0;

}

本案例运行效果如下:

原始数组是:

1 4 6 9 13 16 19 28 40 100

插入一个新的数字: 10

1 4 6 9 10 13 16 19 28 40 100

本文由IT教学网整理发布,转载请注明出处:http://www.itjx.com/jiaocheng/cyuyan/916.html

联系我们

在线咨询:点击这里给我发消息

咨询电话:400-998-2681

工作时间:7*24小时无休