c语言冒泡排序法升降序对n个整数
时间: 2023-09-27 21:09:09 浏览: 91
以下是C语言实现冒泡排序的代码示例,包括升序和降序排序:
```c
#include <stdio.h>
// 升序冒泡排序
void bubbleSortAsc(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 bubbleSortDesc(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;
}
}
}
}
int main() {
int arr[] = {3, 5, 1, 9, 7};
int n = sizeof(arr) / sizeof(arr[0]);
// 升序排序
bubbleSortAsc(arr, n);
printf("升序排序结果:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 降序排序
bubbleSortDesc(arr, n);
printf("降序排序结果:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果:
```
升序排序结果:1 3 5 7 9
降序排序结果:9 7 5 3 1
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)