求c语言题目!!
谢谢!
由计算机随机产生10个0~100之间的整数存入数组a中,并将这些数从小到大排序,然后输入一个整数x,在数组a中查找x,若找到则输出相应的下标,否则输出“未找到”。
具体要求:
(1)用选择排序法或冒泡排序法进行排序。
(2)用顺序查找法或折半查找法进行查找。
(3)如果要删除查找到的元素值,如何修改程序?
1条回答 默认 最新
- benbenli 2021-05-08 00:17关注
下面是我些的代码和运行结果:
// 由计算机随机产生10个0~100之间的整数存入数组a中,并将这些数从小到大排序,然后输入一个整数x,在数组a中查找x,若找到则输出相应的下标,否则输出“未找到”。 #include <stdlib.h> #include <stdio.h> #define MAX 100 #define N 10 int a[N]; int count = N; void populate() { for (int i = 0; i < count; ++i) { a[i] = rand() % (MAX + 1); } } // 具体要求: (1)用选择排序法或冒泡排序法进行排序。 void bubble_sort() { for (int i = 0; i < count - 1; ++i) for (int j = i + 1; j < count; ++j) if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } // (2)用顺序查找法或折半查找法进行查找。 int find(int x) { for (int i = 0; i < count; ++i) if (a[i] == x) return i; return -1; } // (3)如果要删除查找到的元素值,如何修改程序? int remove(int x) { for (int i = 0; i < count; ++i) if (a[i] == x) { for (int j = i + 1; j < count; ++j) a[j - 1] = a[j]; --count; return i; } return -1; } // 主函数一次调用前面的函数 int main() { int x; int index; populate(); bubble_sort(); printf("Here are the %d numbers:\n", count); for (int i = 0; i < count; ++i) printf("%d ", a[i]); printf("\n"); printf("Please enter a number (0 .. 100) to look for and press ENTER: "); scanf("%d", &x); index = find(x); if (index != -1) printf("Found it! Its index (0-based) is %d\n", index); else printf("Not found.\n"); printf("Please enter a number (0 .. 100) to look for and press ENTER: "); scanf("%d", &x); index = find(x); if (index != -1) printf("Found it! Its index (0-based) is %d\n", index); else printf("Not found.\n"); printf("Please enter a number (0 .. 100) to delete and press ENTER: "); scanf("%d", &x); index = remove(x); if (index != -1) printf("Deleted it! Its index (0-based) was %d\n", index); else printf("Not found.\n"); printf("Here are the %d numbers:\n", count); for (int i = 0; i < count; ++i) printf("%d ", a[i]); printf("\n"); } // Output: Here are the 10 numbers: 8 12 30 32 32 44 52 54 56 94 Please enter a number (0 .. 100) to look for and press ENTER: 44 Found it! Its index (0-based) is 5 Please enter a number (0 .. 100) to look for and press ENTER: 40 Not found. Please enter a number (0 .. 100) to delete and press ENTER: 12 Deleted it! Its index (0-based) was 1 Here are the 9 numbers: 8 30 32 32 44 52 54 56 94
附注:求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载,需要20积分/C币。赞助多少都可以。多谢。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 13无用 1
悬赏问题
- ¥170 如图所示配置eNSP
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改
- ¥20 wireshark抓不到vlan
- ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
- ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
- ¥15 stata安慰剂检验作图但是真实值不出现在图上
- ¥15 c程序不知道为什么得不到结果
- ¥15 键盘指令混乱情况下的启动盘系统重装