请用c语言编写一段程序,要求如下:任意输入6个整数,应用选择排序将数据从低到高排序。
时间: 2024-05-15 10:17:57 浏览: 18
好的,我可以为您编写这段程序。以下是C语言代码:
```
#include <stdio.h>
void selection_sort(int arr[], int n) {
int i, j, min_idx, temp;
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;
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[6], i;
printf("请输入6个整数:\n");
for (i = 0; i < 6; i++)
scanf("%d", &arr[i]);
selection_sort(arr, 6);
printf("排序后的结果如下:\n");
for (i = 0; i < 6; i++)
printf("%d ", arr[i]);
return 0;
}
```
这个程序会先读入6个整数,然后应用选择排序算法将它们从低到高排序,最后输出排序后的结果。
相关问题
请用c语言编写一段程序,要求如下:任意输入6个整数,应用选择排序将数据从低到高排序。注意:程序请尽量简洁并给出分析
Sure, I can help you with that. Here's the code in C language using selection sort algorithm to sort 6 integers in ascending order:
```c
#include <stdio.h>
int main() {
int arr[6], i, j, temp, min;
printf("Enter 6 integers: ");
for (i = 0; i < 6; i++) {
scanf("%d", &arr[i]);
}
// Selection sort
for (i = 0; i < 5; i++) {
min = i;
for (j = i + 1; j < 6; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
// Display sorted array
printf("Sorted array: ");
for (i = 0; i < 6; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
The program starts by declaring an integer array of size 6 and variables i, j, temp, and min. Then, the user is prompted to enter 6 integers which are stored in the array.
The selection sort algorithm is then used to sort the array in ascending order. In this algorithm, we iterate through each element of the array and find the minimum element from the remaining unsorted elements. We swap the minimum element with the current element, thus placing the minimum element in its correct position. We repeat this process until the whole array is sorted.
Finally, the sorted array is displayed on the screen using a for loop.
I hope this helps! Let me know if you have any further questions or if there's anything else I can assist you with.
用c语言编写一段程序,要求:利用指针将由键盘输入的任意十个整数排序。
下面是一段使用指针将输入的十个整数排序的C语言程序:
```c
#include <stdio.h>
void sort(int *arr, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (*(arr + i) > *(arr + j)) {
temp = *(arr + i);
*(arr + i) = *(arr + j);
*(arr + j) = temp;
}
}
}
}
int main() {
int arr[10];
int i, n = 10;
printf("Enter ten numbers: ");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
sort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++) {
printf("%d ", *(arr + i));
}
return 0;
}
```
这个程序中,我们首先定义了一个 `sort` 函数,用于排序。该函数接受一个整数数组的指针和数组长度作为参数。在函数内部,我们使用两个嵌套的循环来比较并交换数组元素的位置,从而实现排序。
在 `main` 函数中,我们创建一个长度为10的整数数组,并使用 `scanf` 函数从键盘读取10个整数。然后,我们调用 `sort` 函数将数组排序,并使用指针来访问和打印数组元素。
最终,程序将按升序打印排序后的数组。