C语言,用选择法对数组中的10个数按由大到小排序
时间: 2023-12-03 20:43:18 浏览: 58
以下是用选择法对数组中的10个数按由大到小排序的C语言代码:
```c
#include <stdio.h>
int main() {
int arr[10] = {3, 7, 1, 9, 2, 6, 4, 10, 8, 5};
int i, j, maxIndex, temp;
// 选择排序
for (i = 0; i < 9; i++) {
maxIndex = i;
for (j = i + 1; j < 10; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
// 输出排序结果
printf("排序后的数组为:");
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行结果:
```
排序后的数组为:10 9 8 7 6 5 4 3 2 1
```
相关问题
用c语言用选择法对数组中10个整数按由小到大排序
下面是使用选择排序法对一个整型数组按照从小到大的顺序进行排序的C语言代码:
```c
#include <stdio.h>
void selectionSort(int arr[], int n);
int main() {
int arr[] = {64, 25, 12, 22, 11, 90, 87, 78, 56, 36};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nSorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
void selectionSort(int 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;
}
}
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
输出结果:
```
Original array:
64 25 12 22 11 90 87 78 56 36
Sorted array:
11 12 22 25 36 56 64 78 87 90
```
c语言用选择法对数组中10个整数按由小到大排序的代码
以下是用选择排序法对数组进行排序的C语言代码:
```c
#include <stdio.h>
void selectionSort(int arr[], int n);
int main() {
int arr[10] = { 5, 3, 8, 6, 2, 7, 1, 9, 4, 0 };
int n = sizeof(arr) / sizeof(int);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
```
这个程序使用了选择排序算法,对数组中的10个整数进行排序。排序后的结果会输出到控制台上。
相关推荐
![](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)