排序算法--希尔排序

希尔排序是插入排序的改进版本,适合中等规模数据排序,性能优于简单插入排序。

cpp 复制代码
// 希尔排序函数
void shellSort(int arr[], int n) {
    // 初始间隔(gap)为数组长度的一半,逐步缩小
    for (int gap = n / 2; gap > 0; gap /= 2) {
        // 对每个间隔进行插入排序
        for (int i = gap; i < n; i++) {
            int temp = arr[i]; // 当前需要插入的元素
            int j;

            // 将比 temp 大的元素向后移动
            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) {
                arr[j] = arr[j - gap];
            }
            arr[j] = temp; // 插入 temp 到正确位置
        }
    }
}
cpp 复制代码
#include <stdio.h>
// 打印数组函数
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {12, 34, 54, 2, 3}; // 待排序数组
    int n = sizeof(arr) / sizeof(arr[0]); // 计算数组长度

    printf("排序前的数组: \n");
    printArray(arr, n);

    shellSort(arr, n); // 调用希尔排序函数

    printf("排序后的数组: \n");
    printArray(arr, n);

    return 0;
}

优化建议

1.优化间隔序列:使用更高效的间隔序列(如 Hibbard 或 Sedgewick 序列)可以提升性能。

cpp 复制代码
void shellSortOptimized(int arr[], int n) {
    int gaps[] = {701, 301, 132, 57, 23, 10, 4, 1}; // Sedgewick 序列
    int gapsSize = sizeof(gaps) / sizeof(gaps[0]);

    for (int k = 0; k < gapsSize; k++) {
        int gap = gaps[k];
        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;
        }
    }
}

2.结合插入排序:当间隔缩小到 1 时,希尔排序退化为插入排序,适合小规模数据。

3.稳定性:希尔排序是不稳定的排序算法(相同元素的相对顺序可能改变)。

相关推荐
W_chuanqi5 分钟前
RDEx:一种效果驱动的混合单目标优化器,自适应选择与融合多种算子与策略
人工智能·算法·机器学习·性能优化
L_090719 分钟前
【Algorithm】二分查找算法
c++·算法·leetcode
靠近彗星22 分钟前
3.3栈与队列的应用
数据结构·算法
祁同伟.1 小时前
【C++】多态
开发语言·c++
rechol1 小时前
C++ 继承笔记
java·c++·笔记
朱嘉鼎2 小时前
C语言之可变参函数
c语言·开发语言
SunkingYang2 小时前
详细介绍C++中捕获异常类型的方式有哪些,分别用于哪些情形,哪些异常捕获可用于通过OLE操作excel异常
c++·excel·mfc·异常捕获·comerror
while(1){yan}2 小时前
数据结构之链表
数据结构·链表
Han.miracle4 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
北冥湖畔的燕雀5 小时前
C++泛型编程(函数模板以及类模板)
开发语言·c++