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 函数对数组进行排序,并输出排序前后的数组内容。希尔排序通过不断缩小增量的方式,可以更有效地减少逆序对的数量,提高排序效率。

相关推荐
eggwyw8 小时前
C++ union 的一种妙用法
开发语言·c++
ShineWinsu10 小时前
对于Qt:QHBoxLayout常见属性以及方法的解析
c++·qt·面试·gui·客户端·布局管理器·水平布局器
小七在进步11 小时前
string的实现(1)
c++·笔记·visual studio
敲上瘾13 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
牢姐与蒯14 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251115 小时前
[C++] C++11
开发语言·c++·笔记
小小bugbug19 小时前
带工作窃取的线程池
c++·线程池
南风84111 天前
C++ 四种强制类型转换详解
c++
微笑星河q1 天前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
HaiXCoder2 天前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++