编写主函数实现对冒泡怕排序和选择排序函数的调用,并对每趟排序结果进行打印。
时间: 2023-07-15 18:14:58 浏览: 48
以下是一个简单的示例代码,实现了冒泡排序和选择排序的调用,并打印每趟排序结果:
```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-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
// 打印每趟排序结果
cout << "第" << i+1 << "趟排序结果:";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
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]);
// 打印每趟排序结果
cout << "第" << i+1 << "趟排序结果:";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
int main() {
int arr1[] = {3, 1, 4, 5, 2};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
cout << "冒泡排序:" << endl;
bubbleSort(arr1, n1);
cout << "最终排序结果:";
for (int i = 0; i < n1; i++) {
cout << arr1[i] << " ";
}
cout << endl << endl;
int arr2[] = {3, 1, 4, 5, 2};
int n2 = sizeof(arr2) / sizeof(arr2[0]);
cout << "选择排序:" << endl;
selectionSort(arr2, n2);
cout << "最终排序结果:";
for (int i = 0; i < n2; i++) {
cout << arr2[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果:
```
冒泡排序:
第1趟排序结果:1 3 4 2 5
第2趟排序结果:1 3 2 4 5
第3趟排序结果:1 2 3 4 5
第4趟排序结果:1 2 3 4 5
最终排序结果:1 2 3 4 5
选择排序:
第1趟排序结果:1 3 4 5 2
第2趟排序结果:1 2 4 5 3
第3趟排序结果:1 2 3 5 4
第4趟排序结果:1 2 3 4 5
最终排序结果:1 2 3 4 5
```