Problem F: 零起点学算法85——数组中插入一个数
Description
给定有序数组(从小到大),再给你一个数,要求插入该数到数组中并保持顺序
Input
多组测试,每组第一行输入一个整数n,然后是n个有序的整数 第二行输入1个整数m和1个整数K
Output
将整数m插入到原数组中保持顺序是升序,然后输出2行 第一行是插入以后的数组 第二行是插入以后的数组中下标值是K的数 n m k不超过20
Sample Input
3 1 2 5
3 1
Sample Output
1 2 3 5
2
#include<stdio.h>
int main(){
int a[100],n,i,k,b[100],j,m=0;
while(scanf("%d",&n)!=EOF){
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d%d",&k,&j);
for(i=0;i<n;i++){
if(a[i]<k){
b[m]=a[i];
m++;
}
else{
b[m]=k;
m++;
break;
}
}
for(i=m-1;i<n;i++){
b[m]=a[i];
m++;
}
for(i=0;i<m-1;i++){
printf("%d ",b[i]);
}
printf("%d\n",b[m-1]);
printf("%d\n",b[j]);
}
return 0;
}
总结
1、对于换行符要精确使用。
2、对于数组的删减增加常常建立对应新数组,然后将保留的数字赋值过去。