網站首頁 編程語言 正文
1.代碼模板
// 希爾排序(Shell Sort) void ShellSort(SqList *L) { int i, j; int increment = L->length; // 先讓增量初始化為序列的長度 do { increment = increment / 3 + 1; // 計算增量的值 for (i = increment + 1; i <= L->length; i ++ ) { if (L->arr[i] < L->arr[i - increment]) { // 如果L->[i]需要插入有序增量子表 L->arr[0] = L->arr[i]; // 暫存在哨兵位 for (j = i - increment; j > 0 && L->arr[0] < L->arr[j]; j -= increment) { // 遍歷增量子表,尋找插入位置 L->arr[j + increment] = L->arr[j]; } L->arr[j+increment] = L->arr[0]; // 插入 } } } while (increment > 1); }
2.算法介紹
希爾排序,又叫縮小增量排序,算法屬于插入類排序的進階算法,采取跳躍分割的策略,將關鍵字較小的元素跳躍式的往前挪,大大減小了交換比較的次數。使得序列整體基本有序 ,即大的元素基本在后面,小的元素基本在前面,不大不小的元素基本在中間。
希爾排序的關鍵在于將序列中相隔某個“增量”的元素組成一個子序列,且序列的最后一個增量必須為1,這樣才能保證最后的結果是有序且正確的。但增量如何選擇為最佳,至今仍無定論。且由于元素是跳躍式移動的,所有希爾排序是一個不穩定的排序算法,其時間復雜度受到增量選擇的影響,最好為O(n^1.3) , 最壞為O(n*n)。
3.實例
#include <iostream> using namespace std; const int N = 100; typedef struct { int arr[N]; // 存儲待排序的序列 int length; // 存儲序列的長度 } SqList; void ShellSort(SqList *L) { int i, j; int increment = L->length; do { increment = increment / 3 + 1; for (i = increment + 1; i <= L->length; i ++ ) { if (L->arr[i] < L->arr[i - increment]) { L->arr[0] = L->arr[i]; for (j = i - increment; j > 0 && L->arr[0] < L->arr[j]; j -= increment) L->arr[j + increment] = L->arr[j]; L->arr[j + increment] = L->arr[0]; } } } while (increment > 1); } int main() { SqList L; L.arr[1] = 50; L.arr[2] = 10; L.arr[3] = 90; L.arr[4] = 30; L.arr[5] = 70; L.arr[6] = 40; L.arr[7] = 80; L.arr[8] = 60; L.arr[9] = 20; L.length = 9; ShellSort(&L); for (int i = 1; i <= L.length; i ++ ) cout << L.arr[i] << " "; }
原文鏈接:https://blog.csdn.net/weixin_51424157/article/details/122344532
相關推薦
- 2022-09-22 matplotlib自定義風格
- 2023-03-01 Golang?Makefile示例深入講解使用_Golang
- 2022-11-07 Python運算符之Inplace運算符的使用教程_python
- 2022-04-25 Pycharm報錯:'NoneType'?object?has?no?attribute?'byte
- 2022-06-07 victoriaMetrics庫布隆過濾器初始化及使用詳解_Golang
- 2022-07-22 yaml文件的加載使用
- 2022-03-30 c語言static關鍵字用法詳解_C 語言
- 2022-09-19 Python?matplotlib數據可視化圖繪制_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支