题目描述
设置一个可以存放1000个整数的数据集合(一维数组),输入一个整数n,输入n个整数存放在集合中。利用冒泡法对集合进行由大到小排序,输入一个整数x,插入排序后的集合中,使得数组依然有序。
输入
第一行一个整数n。
第二行 n个整数,赋值给集合。第三行一个整数x,为插入数据。
输出
第一行 请输入实际元素个数n:提示输入集合元素个数第二行 输出插入新数据之后的集合。
示例如下
输入
5
12 36 54 78 98
36
输出
98 78 54 36 36 12
案例代码
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n;
printf("请输入实际元素个数n:");
scanf("%d", &n);
int arr[1000];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubbleSort(arr, n);
int x;
scanf("%d", &x);
int insertIndex = -1;
for (int i = 0; i < n; i++) {
if (arr[i] <= x) {
insertIndex = i;
break;
}
}
for (int i = n; i > insertIndex; i--) {
arr[i] = arr[i - 1];
}
arr[insertIndex] = x;
// 输出插入新数据之后的集合
for (int i = 0; i <= n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
运行截图
© 版权声明
本站提供的资源,都来自网络,版权争议与本站无关,所有内容及软件的文章仅限用于学习和研究目的。不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负,我们不保证内容的长久可用性,通过使用本站内容随之而来的风险与本站无关,您必须在下载后的24个小时之内,从您的电脑/手机中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。侵删请致信E-mail:317608094@qq.com
THE END
暂无评论内容