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

相关推荐
散峰而望1 天前
【算法竞赛】链表和 list
数据结构·c++·算法·链表·list·哈希算法·推荐算法
郝学胜-神的一滴1 天前
Qt OpenGL 生成Mipmap技术详解
开发语言·c++·qt·系统架构·游戏引擎·图形渲染·unreal engine
w-w0w-w1 天前
C++中vector的操作和简单实现
开发语言·数据结构·c++
Larry_Yanan1 天前
Qt安卓开发(一)Qt6.10环境配置
android·开发语言·c++·qt·学习·ui
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——力扣 227 题:基本计算机Ⅱ
c++·算法·leetcode·职场和发展·结构于算法
Z1Jxxx1 天前
整除整除整除
开发语言·c++·算法
dlpay1 天前
Visual Studio 2022中使用websocketpp
c++·ide·visual studio·boost·websocketpp
云雾J视界1 天前
从Boost的设计哲学到工业实践:解锁下一代AI中间件架构的密码
c++·人工智能·中间件·架构·stackoverflow·boost
CSDN_RTKLIB1 天前
【std::vector】resize元素处理方式
c++·stl
彩妙不是菜喵1 天前
C++:类与对象
开发语言·c++