用选择法对10个整数排序。cpp
时间: 2023-06-12 07:05:46 浏览: 46
以下是使用选择排序算法对10个整数进行排序的C++代码:
```cpp
#include <iostream>
using namespace std;
int main() {
int arr[10] = {5, 9, 3, 7, 1, 8, 2, 4, 6, 0}; // 10个整数数组
int n = 10; // 数组元素数量
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;
}
// 输出排序后的数组
cout << "排序后的数组:";
for (i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
排序后的数组:0 1 2 3 4 5 6 7 8 9
```
相关问题
用选择法对10个整数排序cpp
以下是使用选择排序法对10个整数进行排序的C++代码:
```cpp
#include<iostream>
using namespace std;
int main() {
int arr[10] = {5, 2, 9, 3, 7, 8, 6, 1, 4, 0};
int n = 10;
// 使用选择排序法进行排序
for (int i = 0; i < n-1; i++) {
int min_index = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
int temp = arr[min_index];
arr[min_index] = arr[i];
arr[i] = temp;
}
// 输出排序后的结果
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
这段代码中,我们先定义了一个包含10个整数的数组arr,然后使用选择排序法进行排序。选择排序法的基本思路是,每次从未排序的部分中选出最小的元素,然后放到已排序的部分的末尾。这样经过n-1轮排序后,整个数组就被排序完成了。最后我们输出排序后的结果。
用选择法对任意10个整数排序cpp
下面是使用选择排序算法对10个整数进行排序的cpp代码:
```cpp
#include <iostream>
using namespace std;
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;
swap(arr[min_idx], arr[i]);
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11, 1, 3, 7, 17, 19};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
for (int i=0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
```
输出结果:
```
Sorted array:
1 3 7 11 12 17 19 22 25 64
```
在这个程序中,我们定义了一个名为`selectionSort`的函数来实现选择排序算法。该函数接受两个参数:待排序的数组和数组的大小。在函数内部,我们使用两个for循环来遍历数组,找到未排序部分的最小元素并将其交换到已排序部分的最右端。最后,我们在主函数中调用`selectionSort`函数并输出排序后的数组。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)