C++ 容器实现 Shell 排序算法
以下是使用 C++ 容器完成 Shell 排序的示例代码:
#include <iostream>
#include <vector>
using namespace std;
void shellSort(vector<int>& arr) {
int n = arr.size();
// 使用希尔增量序列
for (int gap = n / 2; gap > 0; gap /= 2) {
// 对每个增量进行插入排序
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
arr[j] = arr[j - gap];
}
arr[j] = temp;
}
}
}
int main() {
vector<int> arr = {9, 5, 2, 7, 1, 8};
shellSort(arr);
cout << '排序结果:';
for (int num : arr) {
cout << num << ' ';
}
cout << endl;
return 0;
}
该代码使用了 C++ STL 中的 vector 容器来存储待排序的元素。shellSort 函数实现了希尔排序算法,使用希尔增量序列对元素进行分组,然后对每个分组进行插入排序。最后,通过遍历容器输出排序结果。
运行该代码,输出结果为:
排序结果:1 2 5 7 8 9
原文地址: https://www.cveoy.top/t/topic/qAyi 著作权归作者所有。请勿转载和采集!