c语言分别用“冒泡法”对 10 个整数按由小到大排序。不用定义函数,10 个整数为 35、68、 97、2、56、7、9、144、74、5
时间: 2023-07-10 09:29:46 浏览: 31
好的,这里是使用 C 语言实现冒泡排序的代码:
```c
#include <stdio.h>
int main() {
int arr[] = { 35, 68, 97, 2, 56, 7, 9, 144, 74, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("排序结果:");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
排序结果:2 5 7 9 35 56 68 74 97 144
```
相关问题
使用C语言函数,用选择法对数组中10个整数按由小到大排序。
可以使用以下C语言代码实现选择排序:
```c
#include <stdio.h>
void selection_sort(int arr[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
int main() {
int arr[10] = {9, 3, 5, 1, 7, 2, 8, 4, 6, 0};
int i;
printf("Before sorting:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
selection_sort(arr, 10);
printf("After sorting:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
Before sorting:
9 3 5 1 7 2 8 4 6 0
After sorting:
0 1 2 3 4 5 6 7 8 9
```
以上代码中,`selection_sort` 函数实现了选择排序算法。在 `main` 函数中,我们定义了一个包含10个整数的数组 `arr` ,并打印出排序前的数组元素。然后调用 `selection_sort` 函数对数组进行排序,并打印出排序后的数组元素。
使用c语言用冒泡法分别对输入的十个整数由大到小排序
好的,以下是使用冒泡排序法对输入的十个整数由大到小排序的C语言代码:
```c
#include <stdio.h>
void bubble_sort(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[10], i;
printf("请输入十个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
bubble_sort(arr, 10);
printf("排序后的结果为:\n");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
在上面的代码中,我们定义了一个`bubble_sort`函数来进行冒泡排序,然后在`main`函数中读入十个整数,调用`bubble_sort`函数进行排序,并输出排序后的结果。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)