c语言利用数组用选择法对10个数从大到小排序
时间: 2024-06-13 08:09:44 浏览: 7
以下是C语言利用数组用选择法对10个数从大到小排序的代码示例:
```c
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, maxIndex, tmp;
for (i = 0; i < n - 1; i++) {
maxIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
tmp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = tmp;
}
}
int main() {
int arr[10], i;
printf("请输入10个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
selectionSort(arr, 10);
printf("由大到小顺序为:\n");
for (i = 0; i < 10; i++) {
printf("%3d", arr[i]);
}
return 0;
}
```
相关问题
用c语言利用数组和起泡法对五个数由大到小排序。
以下是使用 C 语言利用数组和冒泡排序法对五个数由大到小排序的示例代码:
```c
#include <stdio.h>
int main() {
int arr[5], i, j, temp;
printf("Enter 5 numbers: ");
for (i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
// 冒泡排序法
for (i = 0; i < 5; i++) {
for (j = 0; j < 4 - i; j++) {
if (arr[j] < arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in descending order: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
代码执行过程如下:
1. 定义一个包含 5 个元素的整型数组 `arr`。
2. 提示用户输入 5 个数,并将它们存储到数组中。
3. 使用冒泡排序法对数组进行排序,使得数组中的数从大到小排列。
4. 输出排序后的数组元素。
C语言 利用数组和起泡法对五个数由大到小排序
以下是 C 语言利用数组和冒泡排序算法对五个数由大到小排序的示例代码:
```c
#include <stdio.h>
int main() {
int nums[5] = {5, 3, 1, 4, 2}; // 待排序的五个数
int i, j, temp;
// 冒泡排序
for (i = 0; i < 4; i++) {
for (j = 0; j < 4 - i; j++) {
if (nums[j] < nums[j+1]) { // 如果前一个数比后一个数小
// 交换两个数的位置
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
// 输出排序后的结果
for (i = 0; i < 5; i++) {
printf("%d ", nums[i]);
}
return 0;
}
```
运行结果为:
```
5 4 3 2 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)