6.编写程序从控制台接收用户输入的10个数,采用冒泡排序和选择排序两种方式进行排序,并将原数据和排序后的数据打印输出。生成c语言代码
时间: 2024-03-17 14:46:22 浏览: 48
以下是 C 语言代码实现:
```c
#include <stdio.h>
// 冒泡排序
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// 选择排序
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main() {
int i, arr[10];
// 从控制台接收用户输入的10个数
printf("请输入10个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 冒泡排序
bubbleSort(arr, 10);
printf("冒泡排序结果:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 选择排序
selectionSort(arr, 10);
printf("选择排序结果:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
程序中定义了两个函数 bubbleSort 和 selectionSort,分别实现冒泡排序和选择排序。首先从控制台接收用户输入的 10 个数,然后对这 10 个数进行冒泡排序和选择排序,最后打印输出排序前后的结果。
运行上述代码,可以得到如下输出结果:
```
请输入10个整数:
9 5 2 4 0 6 3 1 8 7
冒泡排序结果:
0 1 2 3 4 5 6 7 8 9
选择排序结果:
0 1 2 3 4 5 6 7 8 9
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)