阿米诺斯

This commit is contained in:
2024-12-22 15:44:24 +08:00
parent cbf7e4467e
commit 23f1c1c35e
2 changed files with 51 additions and 0 deletions
+1
View File
@@ -4,3 +4,4 @@ project(homework8)
set(CMAKE_CXX_STANDARD 20)
add_executable(test1 test1.cpp)
add_executable(test2 test2.cpp)
+50
View File
@@ -0,0 +1,50 @@
// 编写一个程序,实现冒泡排序算法。用相关数据进行测试,并输出各趟的排序结果。
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
void BubbleSort(vector<T> &v) {
int count = 1;
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v.size() - i - 1; j++) {
cout << "正在进行第" << count << "次排序,";
if (v[j] > v[j + 1]) {
cout << "交换" << v[i] << "" << v[j] << endl;
T temp = v[j];
v[j] = v[j + 1];
v[j + 1] = temp;
}
cout << "交换后:" << endl;
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
count++;
}
}
}
int main() {
vector<int> v = {1, 3, 2, 4, 6, 5, 7, 10, 9, 8};
vector<int>::iterator it;
cout << "排序前:" << endl;
for (it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
BubbleSort(v);
cout << "排序后:" << endl;
for (it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}