c语言向一个已经排好序的数组中插入一个整数,保持原来的顺序不变

要求:
1画出算法流程图。
2整数组由直接赋值方式初始化,要插入的整数由scanf()函数输入。
3算法实现过程采用指针处理。
4输出原始数组数据以及插入整数后的数组证据,并加以说明。

#include<stdio.h>

void main(void)
{
int str[10] = {1,2,3,4,5,6,7,8};
int temp1,temp2,*q,*p = str;
for(;p<str+8;p++)
printf("%d ",*p);
printf("\n请输入要插入的数据:");
scanf("%d",&temp1);
printf("请输入插入地方的数据(左插):");
scanf("%d",&temp2);
for(p=str;p<str+8;p++) //查找插入的位置
if(*p==temp2)
break;
if(p==str+8) //判断是否找到插入地方的数据
{
printf("被插入的数据不存在,插入数据将排在最后面:\n");
*p = temp1;
}
else
{
for(q=str+8;q>=p;q--) //向后赋值 str[i+1]=str[i];
*(q+1)=*q;

*p =temp1; //给当前位置赋所要插入的值。
}
for(p=str;p<str+9;p++)
printf("%d ",*p);
printf("\n");

}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-12-11
#include<stdio.h>
int main()
{
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int i, j;
int n;
printf("input a number:\n");
scanf("%d", &n);
for (i = 8; i >= 0; i--)
{
if (a[i] <= n)
{
n = a[i + 1];
break;
}
for (j = 8; j > i; j--)
a[j + 1] = a[j];
}
}

for (i = 0; i < 10; i++)
printf("%d\t", a[i]);
printf("\n");
return 0;
}