c++希尔排序

希尔排序(Shell Sort)是一种插入排序的改进版本,它是非稳定排序算法。希尔排序的基本思想是将待排序的元素分成若干个小组,对每组进行插入排序,然后逐步减小增量,继续按组进行插入排序操作,直至增量为1,最后对整个序列进行一次插入排序。

以下是一个使用 C++ 实现的希尔排序示例:

cpp 复制代码
#include <iostream>
#include <vector>

void shellSort(std::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() {
    std::vector<int> arr = {12, 34, 54, 2, 3};
    
    std::cout << "Original array:";
    for (int num : arr) {
        std::cout << " " << num;
    }
    std::cout << std::endl;
    
    shellSort(arr);
    
    std::cout << "Sorted array:";
    for (int num : arr) {
        std::cout << " " << num;
    }
    std::cout << std::endl;
    
    return 0;
}

在这个示例中,我们首先定义了一个 shellSort 函数用于实现希尔排序,然后在 main 函数中初始化一个整数数组,调用 shellSort 函数对数组进行排序,并输出排序前后的数组内容。希尔排序通过不断缩小增量的方式,可以更有效地减少逆序对的数量,提高排序效率。

相关推荐
历程里程碑21 小时前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode
Tandy12356_1 天前
手写TCP/IP协议栈——TCP结构定义与基本接口实现
c语言·网络·c++·网络协议·tcp/ip·计算机网络
Helibo441 天前
2025年12月gesp3级题解
数据结构·c++·算法
西幻凌云1 天前
初始——正则表达式
c++·正则表达式·1024程序员节
沧澜sincerely1 天前
蓝桥杯101 拉马车
c++·蓝桥杯·stl
w-w0w-w1 天前
运算符重载
c++
持梦远方1 天前
持梦行文本编辑器(cmyfEdit):架构设计与十大核心功能实现详解
开发语言·数据结构·c++·算法·microsoft·visual studio
小灰灰搞电子1 天前
C++ 文件操作详解
开发语言·c++·文件操作
im_AMBER1 天前
Leetcode 90 最佳观光组合
数据结构·c++·笔记·学习·算法·leetcode
Trouvaille ~1 天前
【C++篇】智能指针详解(一):从问题到解决方案
开发语言·c++·c++11·类和对象·智能指针·raii