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

排序 - 希尔排序(缩小增量排序)

时间:2015-07-05 16:53:39      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:希尔排序   排序   

排序过程:先取一个正整数d1 < n, 把所有相隔d1的记录放一组,每个组内进行直接插入排序;然后d2 < d1,重复上述分组和排序操作;直至di = 1,即所有记录放进一个组中排序为止。

希尔排序是不稳定的。

技术分享

代码:

#include <iostream>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;

int arr[10000];

void shellSort(int *a, int len)
{
	int gap = len;
	do {
		gap = gap / 3 + 1; // 业界统一实验的,平均最好情况,经过若干次后,收敛为1
		for (int i = gap; i < len; i += gap) {
			int k = i;
			int tmp = a[k];

			for (int j = i - gap; j >= 0 && a[j] > tmp; j -= gap) {
				a[j + gap] = a[j];
				k = j;
			}
			a[k] = tmp;
		}
	} while (gap > 1);
}

void printArray(int *a, int len)
{
	for (int i = 0; i < len; i++) {
		if (i != 0 && i % 10 == 0) {
			cout << endl;
		}
		cout << setw(3) << a[i] << ' ';
	}
	cout << endl;
}

int main()
{
	srand(time(0));
	cout << "Please input length of array: ";
	int len;
	cin >> len;
	for (int i = 0; i < len; i++) {
		arr[i] = rand() % 100;
	}
	cout << "Before sorting:\n";
	printArray(arr, len);
	shellSort(arr, len);
	cout << "After sorting:\n";
	printArray(arr, len);

	return 0;
}

/*
Please input length of array: 20
Before sorting:
15  40  55   7  80  67  17  36  23  96
54  29  85  81  57  77  63  54  28  78
After sorting:
 7  15  17  23  28  29  36  40  54  54
55  57  63  67  77  78  80  81  85  96
*/


版权声明:本文为博主原创文章,未经博主允许不得转载。

排序 - 希尔排序(缩小增量排序)

标签:希尔排序   排序   

原文地址:http://blog.csdn.net/zyq522376829/article/details/46763215

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