冒泡选择代码用C语言实现用main函数测试
时间: 2024-02-17 18:59:39 浏览: 10
好的,下面是使用 `main` 函数测试冒泡排序和选择排序的 C 语言代码:
```c
#include <stdio.h>
// 冒泡排序
void bubble_sort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (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;
}
}
}
}
// 选择排序
void selection_sort(int arr[], int n) {
int i, j, min_index;
for (i = 0; i < n - 1; i++) {
min_index = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
int main() {
int arr[] = { 5, 2, 9, 3, 1, 6, 8, 7, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("原数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, n);
printf("冒泡排序后:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int arr2[] = { 5, 2, 9, 3, 1, 6, 8, 7, 4 };
printf("原数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
selection_sort(arr2, n);
printf("选择排序后:");
for (int i = 0; i < n; i++) {
printf("%d ", arr2[i]);
}
printf("\n");
return 0;
}
```
输出结果:
```
原数组:5 2 9 3 1 6 8 7 4
冒泡排序后:1 2 3 4 5 6 7 8 9
原数组:5 2 9 3 1 6 8 7 4
选择排序后:1 2 3 4 5 6 7 8 9
```
以上代码中,我们使用 `main` 函数测试了冒泡排序和选择排序的效果,可以看到排序后的数组已经按照从小到大的顺序排好了序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)