实验七完成

This commit is contained in:
2024-12-22 15:17:41 +08:00
parent 594ab426fd
commit 9604d24ef6
2 changed files with 65 additions and 0 deletions
+1
View File
@@ -4,3 +4,4 @@ project(homework7)
set(CMAKE_CXX_STANDARD 20)
add_executable(test1 test1.cpp)
add_executable(test2 test2.cpp)
+64
View File
@@ -0,0 +1,64 @@
// 编写一个程序,实现折半插入排序算法。用相关数据进行测试,并输出各趟的排序结果。
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
void BinaryInsertSort(vector<T> &v) {
for (size_t i = 1; i < v.size(); ++i) {
T key = v[i];
int low = 0, high = i - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (v[mid] > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
for (int j = i - 1; j >= low; --j) {
v[j + 1] = v[j];
}
v[low] = key;
cout << "" << i << " 趟排序:" << endl;
cout << "插入前:";
for (int k = 0; k < low; ++k) {
cout << v[k] << " ";
}
cout << "(" << key << ") ";
for (int k = low + 1; k < i; ++k) {
cout << v[k] << " ";
}
cout << endl;
cout << "插入后:";
for (int k = 0; k < v.size(); ++k) {
cout << v[k] << " ";
}
cout << endl;
}
}
int main() {
vector<int> v = {1, 3, 6, 4, 2, 5, 7, 10, 9, 8};
cout << "排序前:" << endl;
vector<int>::iterator it;
for (it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
BinaryInsertSort(v);
cout << "排序后:" << endl;
for (it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}