通过函数调用,使用选择法对数组的数字按照从大到小的顺序进行排序
时间: 2024-03-18 22:42:41 浏览: 13
好的,下面是实现选择排序的代码:
```
void selectionSort(int arr[], int n) {
int i, j, max_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++) {
// Find the maximum element in unsorted array
max_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
// Swap the found maximum element with the first element
int temp = arr[i];
arr[i] = arr[max_idx];
arr[max_idx] = temp;
}
}
```
调用该函数的方式如下:
```
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:
```
64 25 22 12 11
```
这段代码使用选择排序算法对数组进行排序,将数组中最大的元素放在最前面,然后继续对剩余元素进行排序,直到整个数组有序为止。