排序算法--希尔排序

实现逻辑

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

输出结果:

相关推荐
CodeWithMe18 分钟前
【C++】线程池
开发语言·c++
wuqingshun3141591 小时前
蓝桥杯 2. 确定字符串是否是另一个的排列
数据结构·c++·算法·职场和发展·蓝桥杯
hu_yuchen2 小时前
C++:BST、AVL、红黑树
开发语言·c++
炯哈哈2 小时前
【上位机——MFC】视图
开发语言·c++·mfc·上位机
我也不曾来过12 小时前
继承(c++版 非常详细版)
开发语言·c++
1白天的黑夜13 小时前
贪心算法-2208.将数组和减半的最小操作数-力扣(LeetCode)
c++·算法·leetcode·贪心算法
AAAA劝导tx3 小时前
List--链表
数据结构·c++·笔记·链表·list
格格Code3 小时前
八大排序——冒泡排序/归并排序
数据结构·算法·排序算法
愚润求学3 小时前
【Linux】进程优先级和进程切换
linux·运维·服务器·c++·笔记
Dream it possible!3 小时前
LeetCode 热题 100_最小路径和(92_64_中等_C++)(多维动态规划)
c++·leetcode·动态规划