排序算法--希尔排序

实现逻辑

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

输出结果:

相关推荐
端平入洛23 分钟前
auto有时不auto
c++
哇哈哈20211 天前
信号量和信号
linux·c++
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马1 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝1 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc1 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼1 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx1 天前
DHU上机打卡D31
开发语言·c++·算法
czxyvX1 天前
020-C++之unordered容器
数据结构·c++
会编程的土豆1 天前
2.25 做题
数据结构·c++·算法