请用c语言应用数组存储用户输入的10个整数,编写算法将该数组按照从小到大的顺序排列好。用户再输入1个整数,编写代码把它插入原数列中,要求仍然保持从小到大有序。 编写程序时应考虑到所插入数的各种可能性(比原来所有的数都小;比原来所有的数都大;在最大数和最小数之间)。 输入格式: 请在一行中输入10整数,数据间以空格为间隔。 再在一行中输入1个待插入的整数。 输出格式: 将插入前后排好的有序序列分别在一行内输出,每个数的显示格式:占3位,右对齐。
时间: 2023-06-27 19:04:42 浏览: 56
以下是C语言代码实现:
```c
#include <stdio.h>
#define SIZE 10
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int arr[SIZE];
int i, n, insertNum;
// 输入10个整数
printf("请输入10个整数:\n");
for (i = 0; i < SIZE; i++) {
scanf("%d", &arr[i]);
}
// 排序
insertionSort(arr, SIZE);
// 输出排序后的数组
printf("排序后的数组:\n");
for (i = 0; i < SIZE; i++) {
printf("%3d", arr[i]);
}
printf("\n");
// 输入待插入的整数
printf("请输入待插入的整数:\n");
scanf("%d", &insertNum);
// 判断待插入数的位置并插入
if (insertNum <= arr[0]) {
for (i = SIZE - 1; i >= 1; i--) {
arr[i] = arr[i - 1];
}
arr[0] = insertNum;
} else if (insertNum >= arr[SIZE - 1]) {
arr[SIZE] = insertNum;
} else {
for (i = 0; i < SIZE - 1; i++) {
if (insertNum >= arr[i] && insertNum <= arr[i + 1]) {
for (int j = SIZE - 1; j >= i + 2; j--) {
arr[j] = arr[j - 1];
}
arr[i + 1] = insertNum;
break;
}
}
}
// 输出插入后的数组
printf("插入后的数组:\n");
for (i = 0; i < SIZE + 1; i++) {
printf("%3d", arr[i]);
}
printf("\n");
return 0;
}
```
输入示例:
```
请输入10个整数:
2 4 6 8 10 12 14 16 18 20
请输入待插入的整数:
15
```
输出示例:
```
排序后的数组:
2 4 6 8 10 12 14 16 18 20
插入后的数组:
2 4 6 8 10 12 14 15 16 18 20
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)