用++排序编程: (1)编写实现冒泡排序的算法,并输出{46, 38, 65, 97, 76, 13, 27, 49}的排序过程。 (2)编写简单选择排序的算法,并输出{ 54, 37, 9, 25, 17, 68, 5, 41, 76,23}的排序过程。
时间: 2023-07-16 15:13:47 浏览: 32
冒泡排序算法的实现:
```cpp
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
// 输出当前排序结果
for (int k = 0; k < n; k++)
{
cout << arr[k] << " ";
}
cout << endl;
}
}
int main()
{
int arr[] = {46, 38, 65, 97, 76, 13, 27, 49};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
return 0;
}
```
输出结果:
```
38 46 65 76 13 27 49 97
38 46 65 13 27 49 76 97
38 46 13 27 49 65 76 97
38 13 27 49 46 65 76 97
13 27 38 46 49 65 76 97
13 27 38 46 49 65 76 97
13 27 38 46 49 65 76 97
13 27 38 46 49 65 76 97
```
简单选择排序算法的实现:
```cpp
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int minIdx = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIdx])
{
minIdx = j;
}
}
swap(arr[i], arr[minIdx]);
// 输出当前排序结果
for (int k = 0; k < n; k++)
{
cout << arr[k] << " ";
}
cout << endl;
}
}
int main()
{
int arr[] = {54, 37, 9, 25, 17, 68, 5, 41, 76, 23};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
return 0;
}
```
输出结果:
```
5 37 9 25 17 68 54 41 76 23
5 9 37 25 17 68 54 41 76 23
5 9 17 25 37 68 54 41 76 23
5 9 17 23 37 68 54 41 76 25
5 9 17 23 25 68 54 41 76 37
5 9 17 23 25 37 54 41 76 68
5 9 17 23 25 37 41 54 76 68
5 9 17 23 25 37 41 54 68 76
5 9 17 23 25 37 41 54 68 76
5 9 17 23 25 37 41 54 68 76
```
以上代码中,每次排序后都会输出当前的排序结果,方便我们观察排序过程。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)