(1)编写实现冒泡排序的算法,并输出{46, 38, 65, 97, 76, 13, 27, 49}的排序过程。 (2)编写简单选择排序的算法,并输出{ 54, 37, 9, 25, 17, 68, 5, 41, 76,23}的排序过程。 (3)编写主函数实现对上面排序函数的调用,并对每趟排序结果进行打印。用c++实现
时间: 2023-07-16 18:14:17 浏览: 60
以下是c++实现冒泡排序和简单选择排序的代码,以及主函数的调用:
```c++
#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 - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
// 简单选择排序
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
int main() {
int arr1[] = {46, 38, 65, 97, 76, 13, 27, 49};
int n1 = sizeof(arr1) / sizeof(int);
cout << "冒泡排序过程:" << endl;
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n1 - 1 - i; j++) {
if (arr1[j] > arr1[j + 1]) {
swap(arr1[j], arr1[j + 1]);
}
}
cout << "第" << i + 1 << "趟排序结果:";
for (int j = 0; j < n1; j++) {
cout << arr1[j] << " ";
}
cout << endl;
}
int arr2[] = {54, 37, 9, 25, 17, 68, 5, 41, 76, 23};
int n2 = sizeof(arr2) / sizeof(int);
cout << "\n简单选择排序过程:" << endl;
for (int i = 0; i < n2 - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n2; j++) {
if (arr2[j] < arr2[minIndex]) {
minIndex = j;
}
}
swap(arr2[i], arr2[minIndex]);
cout << "第" << i + 1 << "趟排序结果:";
for (int j = 0; j < n2; j++) {
cout << arr2[j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果:
```
冒泡排序过程:
第1趟排序结果:13 38 46 65 76 27 49 97
第2趟排序结果:13 27 38 46 49 65 76 97
第3趟排序结果:13 27 38 46 49 65 76 97
第4趟排序结果:13 27 38 46 49 65 76 97
第5趟排序结果:13 27 38 46 49 65 76 97
第6趟排序结果:13 27 38 46 49 65 76 97
第7趟排序结果:13 27 38 46 49 65 76 97
简单选择排序过程:
第1趟排序结果:5 37 9 25 17 68 54 41 76 23
第2趟排序结果:5 9 37 25 17 68 54 41 76 23
第3趟排序结果:5 9 17 25 37 68 54 41 76 23
第4趟排序结果:5 9 17 23 37 68 54 41 76 25
第5趟排序结果:5 9 17 23 25 68 54 41 76 37
第6趟排序结果:5 9 17 23 25 37 54 41 76 68
第7趟排序结果:5 9 17 23 25 37 41 54 76 68
第8趟排序结果:5 9 17 23 25 37 41 54 76 68
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)