C语言用选择法排序,对6个浮点数,这6个浮点数放在数组
时间: 2024-05-16 07:17:28 浏览: 64
下面是使用选择法排序对6个浮点数进行排序的C语言代码:
```c
#include <stdio.h>
void selection_sort(float arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
float temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
float arr[6] = {3.2, 1.5, 4.8, 2.7, 6.0, 0.9};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Before sorting:\n");
for (int i = 0; i < n; i++) {
printf("%.1f ", arr[i]);
}
printf("\n");
selection_sort(arr, n);
printf("After sorting:\n");
for (int i = 0; i < n; i++) {
printf("%.1f ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
Before sorting:
3.2 1.5 4.8 2.7 6.0 0.9
After sorting:
0.9 1.5 2.7 3.2 4.8 6.0
```
阅读全文