排序算法--希尔排序

实现逻辑

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

输出结果:

相关推荐
『往事』&白驹过隙;10 分钟前
C/C++中的格式化输出与输入snprintf&sscanf
linux·c语言·c++·笔记·学习·iot·系统调用
Je1lyfish12 分钟前
CMU15-445 (2026 Spring) Project#1 - Buffer Pool Manager
linux·数据库·c++·后端·链表·课程设计·数据库架构
zyeyeye27 分钟前
自定义类型:结构体
c语言·开发语言·数据结构·c++·算法
俩娃妈教编程1 小时前
2023 年 03 月 二级真题(1)--画三角形
c++·算法·双层循环
航哥的女人1 小时前
C++文件操作
开发语言·c++
L_Aria2 小时前
3824. 【NOIP2014模拟9.9】渴
c++·算法·图论
ShineWinsu2 小时前
对于模拟实现C++list类的详细解析—上
开发语言·数据结构·c++·算法·面试·stl·list
Mr YiRan2 小时前
C++语言类中各个重要函数原理
java·开发语言·c++
stripe-python3 小时前
十二重铲雪法(下)
c++·算法
D_evil__3 小时前
【Effective Modern C++】第五章:右值引用、移动语义和完美转发:29. 认识移动操作的缺点
c++