用选择法对数组中的元素进行从小到大的排序(用函数调用的方式)。
时间: 2024-02-25 22:54:00 浏览: 19
好的,以下是用选择排序对数组进行从小到大排序的函数调用方式的示例代码:
```c++
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
swap(arr[i], arr[min_idx]);
}
}
int main() {
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
在这个示例中,我们首先定义了一个 `selectionSort` 函数,它接受一个整数数组和数组的大小作为参数。在该函数中,我们使用嵌套循环来查找未排序部分中的最小元素,并将其与未排序部分中的第一个元素交换。这样,我们就可以通过重复这个过程来将整个数组排序。
最后,我们在 `main` 函数中定义了一个整数数组,并调用 `selectionSort` 函数来对其进行排序。排序完成后,我们使用循环输出已排序的数组元素。