用c语言用选择法排序,对6个浮点数,这6个浮点数放在数组。从大到小
时间: 2024-02-13 09:06:37 浏览: 80
好的,可以使用以下代码实现:
```c
#include <stdio.h>
void selectionSort(float arr[], int n) {
int i, j, maxIndex;
float temp;
for (i = 0; i < n - 1; i++) {
maxIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
if (maxIndex != i) {
temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
}
int main() {
float arr[6] = {3.2, 1.5, 6.7, 2.4, 5.1, 4.3};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Before sorting:\n");
for (i = 0; i < n; i++) {
printf("%.1f ", arr[i]);
}
printf("\n");
selectionSort(arr, n);
printf("After sorting:\n");
for (i = 0; i < n; i++) {
printf("%.1f ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
Before sorting:
3.2 1.5 6.7 2.4 5.1 4.3
After sorting:
6.7 5.1 4.3 3.2 2.4 1.5
```
阅读全文