用c语言编写一个用选择法对整数数组进行简单排序的函数
时间: 2024-05-05 11:19:52 浏览: 22
好的,下面是用选择法对整数数组进行简单排序的C语言函数:
```c
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;
}
}
```
这个函数的参数包括一个整数数组和数组的大小。它使用选择法对数组进行简单排序,将较小的元素移动到数组的前面。
相关问题
用c语言编写一个程序,对给定的整数数组R采用选择排序法进行从小到大的排序,要求将选择排序过程设计成一个函数。
以下是用C语言编写的选择排序函数:
```c
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;
}
}
```
该函数接受两个参数:整数数组 `arr` 和数组元素个数 `n`。在函数内部,我们使用两个嵌套的循环来遍历数组并选择排序。外部循环从数组的第一个元素开始,一直到倒数第二个元素,用于遍历所有的元素。在内部循环中,我们从外部循环迭代器的下一个元素开始遍历数组,找到未排序部分中最小的元素的下标。然后,我们将该最小元素与未排序部分的末尾元素交换,这样它就成为了已排序部分的最后一个元素。
要使用该函数对给定的整数数组进行排序,你可以按照以下方式调用它:
```c
int main()
{
int R[] = {64, 25, 12, 22, 11};
int n = sizeof(R)/sizeof(R[0]);
selectionSort(R, n);
printf("Sorted array: \n");
printArray(R, n);
return 0;
}
```
在这个例子中,我们创建了一个整数数组 `R`,并将其传递给 `selectionSort()` 函数进行排序。然后,我们使用 `printArray()` 函数来打印排好序的数组。
利用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[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selection_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
在这个示例程序中,我们首先定义了一个 `selection_sort` 函数来执行简单选择排序算法。该函数接受两个参数:一个整数数组和数组的大小。在该函数内部,我们使用两个嵌套的循环来遍历数组,找到最小的元素,并将其移动到当前未排序部分的开头。最后,我们在 `main` 函数中定义并初始化了一个整数数组,然后调用 `selection_sort` 函数并打印排序后的结果。
输出结果为:
```
Sorted array: 11 12 22 25 64
```
希望这可以帮助到你!
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)