已有一个按升序排序的数组,含n个元素。输入整数x,将x插入数组中,使数组元素仍按升序排列。请使用数组实现。
输入
输入包含三行:
第一行是数组元素个数n(1 < n < 20)。
第二行是数组n个元素,相邻两项之间用一个空格隔开。
第三行是待插入的元素x。
输出
输出插入后数组的所有元素,相邻两项之间用一个空格隔开。
#include <stdio.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int n;
scanf("%d",&n);
int a[n],i,j;
for(i=0;i<n;i++)
scanf("%d",&a[i]);
int x,t;
scanf("%d",&x);
int b[n+1];
for(i=0;i<n+1;i++){
if(i==n)
b[i]=x;
else
b[i]=a[i];
}
for(i=0;i<n;i++)
for(j=0;j<n-i;j++)
if(b[j]>b[j+1]){
t=b[j];
b[j]=b[j+1];
b[j+1]=t;
}
for(i=0;i<n+1;i++)
printf("%d ",b[i]);
return 0;
}