用c++实现用选择法队十个整数排序
时间: 2023-11-21 20:08:59 浏览: 44
好的,这是一个关于排序算法的问题。以下是使用选择排序算法对十个整数进行排序的 C 代码:
```
#include <stdio.h>
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;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11, 1, 2, 10, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
```
希望这个代码能够对你有所帮助。
相关问题
c++用选择法对 10个整数排序
以下是使用C++实现选择排序对10个整数排序的示例代码:
```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, 2, 3, 4, 5};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: \n";
for (int i=0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
```
输出结果为:
```
Sorted array:
1 2 3 4 5 11 12 22 25 64
```
用选择法对10个整数从小到大排序。C++
以下是C++代码实现:
```cpp
#include <iostream>
using namespace std;
int main() {
int arr[10] = { 2, 8, 1, 5, 9, 3, 6, 4, 7, 0 };
int len = 10;
// 选择排序
for (int i = 0; i < len - 1; i++) {
int min_index = i;
for (int j = i + 1; j < len; j++) {
if (arr[j] < arr[min_index]) {
min_index = j;
}
}
if (min_index != i) {
int temp = arr[i];
arr[i] = arr[min_index];
arr[min_index] = temp;
}
}
// 输出排序结果
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
该程序使用选择排序对一个包含10个整数的数组进行排序。首先,使用双重循环找出数组中最小的元素,并将其与当前位置的元素交换。在每次迭代中,从当前位置开始,将其与后面的元素进行比较,以确定最小值的索引。如果找到更小的元素,则将其索引存储在min_index中。然后,如果min_index不等于当前位置i,则交换arr[i]和arr[min_index]的值。最后,输出排序后的数组。
相关推荐
![](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)