题解 | #有序序列插入一个数#
有序序列插入一个数
http://www.nowcoder.com/practice/74486aec6fe14d44b509efabf265ee66
#include <stdio.h>
int main() { int n = 0; int arr[51] = {0}; int i = 0; int x = 0; int j = 0;
scanf("%d", &n);
for (i=0; i<n; i++)
{
scanf("%d", &arr[i]);
}
scanf("%d", &x);
if (n == 1)
{
if (x > arr[0])
{
int tmp = x;
x = arr[0];
arr[0] = tmp;
}
printf("%d %d", x, arr[0]);
}
else{
for (i=0; i<n+1; i++)
{
if ((arr[i] >= x && x >= arr[i-1]&& i!=0)||(arr[0]>x&&i==0)||(x>arr[n-1]&&i==n))
{
int a = 0;
int tmp = arr[i];
arr[i] = x;
for (j=i+1; j<n+1; j++)
{
a = arr[j];
arr[j] = tmp;
tmp = a;
}
break;
}
}
for (i=0; i<n+1; i++)
printf("%d ",arr[i]);
}
return 0;
}