使用选择法对10个整数
时间: 2024-03-01 16:46:16 浏览: 19
以下是使用选择法对10个整数进行排序的C语言代码:
```c
#include <stdio.h>
int main() {
int i, j, k, m;
int a[10];
printf("请输入十个整数:\n");
for (i = 0; i < 10; i++) {
scanf("%d", &a[i]); // 用scanf输入数组
}
printf("\n");
for (i = 0; i < 9; i++) {
k = i; // 假设初始值为最大值
for (j = i + 1; j < 10; j++) {
if (a[j] > a[k]) {
k = j; // 求出每一轮比较的最大值
}
}
if (k != i) {
m = a[i];
a[i] = a[k];
a[k] = m; // a[i]和a[k]数值互换,使得该轮比较后a[i]为最大值
}
}
printf("用选择法对十个整数从大到小排序结果为:\n");
for (i = 0; i < 10; i++) {
printf("%5d", a[i]);
}
printf("\n");
return 0;
}
```
相关问题
在c语言使用选择法对10个整数排序。
以下是使用选择排序算法对10个整数进行排序的C语言代码:
```c
#include <stdio.h>
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;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
int main() {
int arr[10] = {5, 3, 9, 1, 8, 2, 7, 10, 4, 6};
int n = 10, i;
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nSorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
代码实现了选择排序算法,首先打印原始数组,然后调用selectionSort函数进行排序,最后打印排序后的数组。运行代码会得到以下输出:
```
Original array: 5 3 9 1 8 2 7 10 4 6
Sorted array: 1 2 3 4 5 6 7 8 9 10
```
c语言用选择法对10个整数排序
以下是使用选择法对10个整数进行排序的C语言代码:
```c
#include <stdio.h>
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;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11, 1, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
printf("排序前的数组:\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
selectionSort(arr, n);
printf("\n排序后的数组:\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
```
输出结果为:
```
排序前的数组:
64 25 12 22 11 1 2 3 4 5
排序后的数组:
1 2 3 4 5 11 12 22 25 64
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)