使用容器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
``
原文地址: http://www.cveoy.top/t/topic/iUyG 著作权归作者所有。请勿转载和采集!