C++实现希尔排序

希尔排序可认为是直接插入排序的升级版,直接插入排序是一位一位的挪动,而希尔排序是将步长设置为一个较大的位置,特点如下:
1.一次移动,移动位置较大,跳跃式的接近排序后的最终位置
2.最后一次只需要少量移动
3.增量移动必须是递减的,最后一个必须是1
3.增量序列应该是互质的
代码如下:

#include <iostream>
#include <vector>
using namespace std;

vector<int> ShellSort(vector<int> list, int length)
{
	vector<int> result = list;
	if (result.empty())
	{
		return result;
	}
	int gap = length;
	while (gap)
	{
		gap = gap / 3 + 1;
		for (int i = gap; i < result.size(); i++)
		{
			int temp = result[i];		
			int j = i - gap;
			for (j; j >= 0 && result[j] > temp; j = j - gap)
			{
				result[j + gap] = result[j];
			}
			result[j + gap] = temp;
		}
		
	}
	return result;
}

int main()
{
	int arr[] = { 6, 4, 8, 9, 2, 3, 1 };
	int length = sizeof(arr) / sizeof(arr[0]);
	vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0]));
	cout << "排序前:" << endl;
	for (int i = 0; i < test.size(); i++) {
		cout << test[i] << " ";
	}
	cout << endl;

	vector<int> result;
	result = ShellSort(test, length);
	cout << "排序后:" << endl;
	for (int j = 0; j < result.size(); j++) 
	{
		cout << result[j] << " ";
	}
	cout << endl;
	return 0;
	system("pause");
	
}

参考:
https://blog.csdn.net/wyl1813240346/article/details/81904878
https://cuijiahua.com/blog/2017/12/algorithm_3.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值