stm32 实现数组内元素从大到小排序
时间: 2023-11-28 21:47:53 浏览: 72
可以使用冒泡排序或快速排序等算法来实现。下面是一种冒泡排序的实现方式:
```c
void bubble_sort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] < arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
这里的 `arr` 是待排序的数组,`len` 是数组的长度。每一轮比较相邻两个元素的大小,如果前一个元素比后一个元素小,则交换它们的位置。经过多轮排序后,数组内的元素就会从大到小排列。
相关问题
stm32数组大小排序
可以使用冒泡排序算法对数组进行大小排序。
以下是一个使用冒泡排序对数组进行升序排序的示例代码:
```c
#include <stdio.h>
void bubble_sort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 9, 1, 3, 7, 6, 2, 8, 4};
int len = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, len);
printf("Sorted array: ");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
Original array: 5 9 1 3 7 6 2 8 4
Sorted array: 1 2 3 4 5 6 7 8 9
```
在上述代码中,函数 `bubble_sort` 用于对数组进行冒泡排序,函数参数 `arr` 表示需要排序的数组,参数 `len` 表示数组的长度。在 `main` 函数中,首先输出原始数组,然后调用 `bubble_sort` 函数对数组进行排序,最后输出排序后的数组。
STM32数组6个元素比较大小和平均
下面是一个示例代码,用于比较数组中的6个元素的大小和计算它们的平均值:
```c
#include <stdio.h>
int main() {
int arr[6] = {5, 10, 2, 8, 1, 7};
int sum = 0;
int max = arr[0], min = arr[0];
for (int i = 0; i < 6; i++) {
sum += arr[i];
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
float average = (float) sum / 6;
printf("Max element in the array: %d\n", max);
printf("Min element in the array: %d\n", min);
printf("Average of elements in the array: %.2f\n", average);
return 0;
}
```
这个程序首先定义了一个包含6个整数的数组,然后使用一个for循环遍历数组中的元素,并计算它们的总和。在循环内部,它还比较了每个元素的大小,并找到了最大值和最小值。最后,程序计算了数组元素的平均值,并将结果打印到控制台上。
相关推荐
![](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)