排序算法--希尔排序

实现逻辑

① 先取一个小于n的整数d1作为第一个增量,把文件的全部记录分成d1个组。

② 所有距离为d1的倍数的记录放在同一个组中,在各组内进行直接插入排序。

③ 取第二个增量d2小于d1重复上述的分组和排序,直至所取的增量dt=1(dt小于dt-l小于...小于d2小于d1),即所有记录放在同一组中进行直接插入排序为止。

cpp 复制代码
void print_array(int a[], int n){
	for (int i = 0; i < n; ++i){
		cout << a[i] << " ";
	}
	cout << endl;
}

void shellSort(int arr[], int nSize)
{
	for(int d = nSize / 2; d >= 1; d = d / 2)
	{
		for(int k = 0; k < d; ++k)
		{
			for(int i = k + d; i < nSize; i = i + d)
			{
				int value = arr[i];
				int ipos = i;
				while((ipos - d) >= 0 && value < arr[ipos - d])
				{
					arr[ipos] = arr[ipos - d];
					ipos = ipos - d;
				}
				arr[ipos] = value;
			}
		}
	}
}

int main(){
	int arr[] = {10, 8, 11, 7, 4, 12, 9, 6, 5, 3};
	int len = sizeof(arr)/sizeof(arr[0]);
	int newArray[10] = {0};
	
	cout << "排序前:";
	print_array(arr, len);

	shellSort(arr, len);
	
	cout << "排序后:";
	print_array(arr, len);
	return 0;
}

输出结果:

相关推荐
biter down几秒前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
ShineWinsu1 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
charlie1145141912 小时前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32
DpHard2 小时前
现代 C++ 中 push 接口为何提供 const T& 与 T&& 两个重载
c++
U-52184F693 小时前
深度解析:从 Qt 的 Q_D 宏说起,C++ 工业级 SDK 是如何保证 ABI 稳定性的
数据库·c++·qt
hz_zhangrl4 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
kyle~5 小时前
C++----函数指针与函数指针类型 返回值类型 (*类型名)(参数列表)
开发语言·c++
努力中的编程者5 小时前
二叉树(C语言底层实现)
c语言·开发语言·数据结构·c++·算法
qq_416018726 小时前
高性能密码学库
开发语言·c++·算法
宵时待雨6 小时前
C++笔记归纳14:AVL树
开发语言·数据结构·c++·笔记·算法