码迷,mamicode.com
首页 > 编程语言 > 详细

Shell Sort(希尔排序)

时间:2018-01-02 21:18:59      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:需要   for   运行时间   增量   模拟   排序算法   排序   step   stream   

  这个排序算法很厉害,我个人很喜欢这个算法,但算法的时间复杂度难计。算法对增量(这里也称作step(步长))的选择也需要注意,只记得个希尔增量的最坏情况为O(n^2)、Hibbard增量的最坏情况为O(n^3/2)(书上有证明),书上说Hibbard增量的希尔排序平均情形运行时间基于模拟的结果被认为是O(n^5/4),但暂时没人证明出这个结果。

  算法的代码实现有许多种,我就把《数据结构与算法分析》上的代码用C++敲了几遍当做学习过了,顺便学习C++,记不得的时候再回来复习。

  书《数据结构与算法分析》中给出的代码如下(希尔增量):

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

class ShellSort {
public:
	void shellSort(vector<int>& nums) {
		for(int Increment = (int)nums.size()/2; Increment > 0; Increment /= 2)
			for(int i = Increment; i < (int)nums.size(); i++) {
				int j, temp = nums[i];
				for(j = i; j >= Increment; j -= Increment)
					if(temp < nums[j - Increment])
						nums[j] = nums[j - Increment];
					else
						break;
				nums[j] = temp;
			}
	}
};

int main() {
	vector<int> nums(5);
	ShellSort shellsort;

	for(int i = 0; i < (int)nums.size(); i++)
		cin >> nums[i];

	for(int i = 0; i < (int)nums.size(); i++)
		cout << nums[i] << ‘ ‘;
	cout << endl;

	shellsort.shellSort(nums);

	for(int i = 0; i < (int)nums.size(); i++)
		cout << nums[i] << ‘ ‘;
	return 0;
}

  

Shell Sort(希尔排序)

标签:需要   for   运行时间   增量   模拟   排序算法   排序   step   stream   

原文地址:https://www.cnblogs.com/darkchii/p/8178915.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!