排序算法--希尔排序

实现逻辑

① 先取一个小于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;
}

输出结果:

相关推荐
AA陈超4 小时前
ASC学习笔记0020:用于定义角色或Actor的默认属性值
c++·笔记·学习·ue5·虚幻引擎
coderxiaohan4 小时前
【C++】仿函数 + 模板进阶
开发语言·c++
思成不止于此6 小时前
深入理解 C++ 多态:从概念到实现的完整解析
开发语言·c++·笔记·学习·多态·c++40周年
布丁写代码7 小时前
GESP C++ 一级 2025年09月真题解析
开发语言·c++·程序人生·学习方法
喵个咪9 小时前
Qt 优雅实现线程安全单例模式(模板化 + 自动清理)
c++·后端·qt
兩尛9 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法
欧阳x天9 小时前
C++入门(一)
c++
小张成长计划..9 小时前
【C++】:priority_queue的理解,使用和模拟实现
c++
Dream it possible!10 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
云泽80810 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list