在主函数中设计一个简单的菜单,用随机生成函数生成一组数,测验冒泡排序
时间: 2024-03-07 15:46:27 浏览: 28
好的,下面是一个简单的菜单,其中包含了一个随机生成函数和一个冒泡排序函数,可以用来测验冒泡排序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 随机生成长度为length的数组
void generateArray(int array[], int length) {
srand((unsigned int) time(NULL));
for (int i = 0; i < length; i++) {
array[i] = rand() % 100;
}
}
// 冒泡排序
void bubbleSort(int array[], int length) {
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
int main() {
int length = 10;
int array[length];
int choice = 0;
while (1) {
printf("1. 生成随机数组\n");
printf("2. 冒泡排序\n");
printf("3. 退出\n");
printf("请输入数字选择操作: ");
scanf("%d", &choice);
switch (choice) {
case 1:
generateArray(array, length);
printf("随机数组为: ");
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
printf("\n");
break;
case 2:
bubbleSort(array, length);
printf("排序后的数组为: ");
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
printf("\n");
break;
case 3:
printf("程序已退出\n");
return 0;
default:
printf("输入错误,请重新输入\n");
break;
}
}
return 0;
}
```
运行程序后,可以输入数字选择操作,其中输入1可以生成随机数组,输入2可以对随机数组进行冒泡排序,输入3可以退出程序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](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)