排序方法3---希尔排序

#include<stdio.h>
#include<iostream>
#define MAXL 100
typedef int KeyType;
typedef char InfoType;
typedef struct
{
	KeyType key;
	InfoType data;
}RecType;
void Display(RecType R[], int n)
{
	for (int i = 0; i < n; i++)
	{
		printf("%d", R[i].key);
	}
	printf("\n");
}
void ShellSort(RecType R[], KeyType keys[], int n)
{
	int i, j, d;
	RecType temp;
	for (int i = 0; i < n; i++)
	{
		R[i].key = keys[i];
	}
	printf("排序前:");
	Display(R, n);
	for (d = n / 2; d>0; d = d / 2)
	{
		for (i = d; i < n; i++)
		{
			temp = R[i];
			j = i - d;
			while (j >= 0 && temp.key<R[j].key)
			{
				R[j + d] = R[j];
				j = j - d;      //和同组的排在前面的数据进行再次比较
			}
			R[j + d] = temp;
		}
		printf("  d = %d:", d);
		Display(R, n);
	}
}
int main()
{
	int n = 10;
	RecType R[MAXL];
	KeyType a[] = { 3,7,4,2,8,1,9,0,5,6 };
	ShellSort(R, a, n);
	printf("排序后:");
	Display(R, n);
	system("pause");
	return 1;
}

在这里插入图片描述

### 希尔排序算法详解 #### 算法概述 希尔排序(Shell Sort),亦称为递减增量排序算法,是对插入排序的一种优化版本[^1]。该算法由Donald Shell于1959年提出,并在论文“A high-speed sorting procedure”中对其进行了详细的阐述[^3]。 #### 工作原理 希尔排序通过比较相隔一定间隔的元素来工作,这些间隔逐渐减少直到变为1。当间隔为1时,希尔排序即成为普通的插入排序。这种策略使得远距离的数据可以更快地移动到接近其最终位置的地方,从而提高了整体性能[^4]。 #### 时间复杂度分析 尽管具体的渐近时间复杂度取决于所使用的间隔序列,但在最坏情况下,希尔排序的时间复杂度通常优于简单的插入排序。对于某些特定的选择间隔序列,平均情况下的表现甚至能够达到接近\( O(n \log n) \)。 #### 实现细节 以下是使用Python编写的希尔排序具体实现: ```python def shell_sort(arr): n = len(arr) gap = n // 2 while gap > 0: for i in range(gap, n): temp = arr[i] j = i while j >= gap and arr[j - gap] > temp: arr[j] = arr[j - gap] j -= gap arr[j] = temp gap //= 2 if __name__ == "__main__": test_array = [64, 34, 25, 12, 22, 11, 90] print("原始数组:", test_array) shell_sort(test_array) print("排序后的数组:", test_array) ``` 这段代码展示了如何利用逐步缩小的间隔来进行多次部分有序化的操作,最后完成整个列表的完全排序过程[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值