使用选择法对数组的10个整数按照从大到小的顺序进行排序
时间: 2024-03-18 07:42:42 浏览: 55
程序分析下列程序的功能是用选择法对-2243计算机软件基础(一)自考本科
好的,下面是一个示例代码,使用选择排序算法对数组进行排序,并按照从大到小的顺序输出排序后的数组元素:
```
#include <iostream>
using namespace std;
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[] = {23, 54, 12, 6, 87, 34, 98, 65, 43, 21};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Original Array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
selectionSort(arr, n);
cout << "Sorted Array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
Original Array: 23 54 12 6 87 34 98 65 43 21
Sorted Array: 98 87 65 54 43 34 23 21 12 6
```
这段代码会先输出原始的数组,然后对数组进行选择排序,最后输出排序后的数组元素,按照从大到小的顺序排列。
阅读全文