用选择法对十个整数排序,用c语言输出
时间: 2023-11-21 12:02:25 浏览: 43
以下是使用选择排序算法对十个整数排序的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[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int arr[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果为:
```
Sorted array: 1 2 3 4 5 6 7 8 9 10
```
相关问题
用选择法对十个整数排序的c语言代码
以下是使用选择排序算法对十个整数进行排序的 C 语言代码:
```c
#include <stdio.h>
void selection_sort(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[] = {9, 4, 2, 8, 7, 5, 1, 3, 6, 0};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selection_sort(arr, n);
printf("\nSorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
输出结果:
```
Original array: 9 4 2 8 7 5 1 3 6 0
Sorted array: 0 1 2 3 4 5 6 7 8 9
```
希望这个代码能够帮到您,如果您有任何其他问题,请继续提问。
c语言用选择法对十个整数排序
好的,以下是用选择法(Selection Sort)对十个整数进行排序的C语言代码:
```c
#include <stdio.h>
int main()
{
int arr[10] = {5, 2, 9, 4, 7, 1, 8, 3, 6, 0}; // 待排序的数组
int i, j, min_idx, temp;
// 选择法排序
for (i = 0; i < 9; i++) {
min_idx = i;
for (j = i + 1; j < 10; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
// 输出排序后的结果
for (i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
以上代码中,我们首先定义了一个包含十个整数的数组 `arr`,然后使用选择法对其进行排序。选择法的基本思想是,每一轮从未排序的元素中选择最小的一个,与当前位置的元素交换位置,直到所有元素都排好序。最后,我们输出排好序后的结果。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)