1。(Q140,10分)编写一个函数void SelectionSort(int score[], int n),用选择排序法实现从低到高排序。在main函数中定义一个数组并通过输入的方式初始化,调用该函数完成排序并在main函数中输出排序好的数组, 输入提示:"please input the number of array:" 输入格式:"%d" 输入提示:"please input numbers:\n" 输入格式:"%d" 输出提示:"the sorted array is:" 输出格式:"%5d"
时间: 2023-07-19 18:23:45 浏览: 171
下面是实现代码:
```c
#include <stdio.h>
void SelectionSort(int score[], int n);
int main() {
int n;
printf("please input the number of array:");
scanf("%d", &n);
int score[n];
printf("please input numbers:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &score[i]);
}
SelectionSort(score, n);
printf("the sorted array is:");
for (int i = 0; i < n; i++) {
printf("%5d", score[i]);
}
return 0;
}
void SelectionSort(int score[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (score[j] < score[minIndex]) {
minIndex = j;
}
}
int temp = score[i];
score[i] = score[minIndex];
score[minIndex] = temp;
}
}
```
运行示例:
```
please input the number of array:5
please input numbers:
3 5 1 4 2
the sorted array is: 1 2 3 4 5
```
阅读全文