题源:http://acm.hdu.edu.cn/showproblem.php?pid=2019
Problem Description
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。
Input
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。
Output
对于每个测试实例,输出插入新的元素后的数列。
Sample Input
3 3
1 2 4
0 0
Sample Output
1 2 3 4
思路:典型的插入排序简化版,因为只排一个数,所以复杂度O(n),把x放在数组最后,往前一个一个比,比前面的数小就交换,大就停下,输出结果即可。
#include<stdio.h>
int main(){
int n,x,a[100];
while(scanf("%d%d",&n,&x)){
if(n==0&&x==0) return 0;
int i;
for(i=0;i<n;i++){ //输入数组
scanf("%d",&a[i]);
}
a[n]=x;
int temp;
for(i=n;i>0;i--){ //处理数组
if(a[i]<a[i-1]){
temp=a[i-1];
a[i-1]=a[i];
a[i]=temp;
}
else break;
}
for(i=0;i<n;i++) //输出数组
printf("%d ",a[i]);
printf("%d\n",a[i]);
}
return 0;
}