题解 | #有序序列插入一个整数#
有序序列插入一个整数
https://www.nowcoder.com/practice/444e87f938464906a1649cff236b102b
#include <stdio.h> int main() { int N, new_num; int index = N;//index的初始值是一个数组不能访问的index值 while (scanf("%d", &N) != EOF) { int a[N]; for(int i = 0; i < N; i++){ scanf("%d", &a[i]); } scanf("%d", &new_num); for(int i = 0; i < N - 1; i++){ //new_num处于中间的情况 if(a[i] <= new_num && new_num <= a[i+1]){ index = i; } } if(new_num <= a[0]) printf("%d ", new_num);//new_num小于最小的数 for(int i = 0; i < N; i++){ if(i != index) printf("%d ", a[i]); else printf("%d %d ", a[i], new_num); } if(new_num >= a[N - 1]) printf("%d", new_num);//new_num大于最大的数 } return 0; }