2 Hill sort

It is an improvement to insertion sort, also known as reduced incremental sort. It belongs to the original order.

 

(1) Ideas:

         First take an integer d1 less than n (array length) as the first increment, and divide all records of the file into (n/d1) groups. All records whose distance is a multiple of d1 are placed in the same group. First perform direct insertion sort in each group; then, take the second increment d2<d1 and repeat the above grouping and sorting until the increment dt=1 (dt<dt-1<...<d2<d1) , That is, all records are placed in the same group for direct insertion sort.

 

(2) Complexity analysis:

(2.1) Time complexity:

         O( n^{s}). 1<s<2, s is generally smaller than 2

(2.2) Space complexity:

         O (1)。

 

(3) Stability:

         Hill sorting is to insert and sort the elements according to the asynchronous length. When the elements are very disordered at the beginning, the step is the largest, so the number of elements in the insertion sort is small and the speed is very fast; when the elements are basically in order, the step The length is small, and insertion sort is very efficient for ordered sequences. Therefore, the time complexity of Hill sorting will be better than o(n²). Due to multiple insertion sorts, we know that an insertion sort is stable and will not change the relative order of the same elements, but in different insertion sort processes, the same elements may move in their respective insertion sorts, and finally their stability will be Disrupted, so the shell sort is unstable.

 

code segment:

void shell_sort(int a[],int n)
{
	int d,i,j,tmp;
	d=n/2;			//分成n/2组
	while(d>=1)
	{
		//对每组进行插入排序
		for(i=d;i<n;i++)
		{
			tmp=a[i];
			for(j=i-d;j>=0&&a[j]>tmp;j=j-d)
			{
				a[j+d]=a[j];
			}
			a[j+d]=tmp;
		}
		d=d/2;		//更新增量d
	}
}

 

Guess you like

Origin blog.csdn.net/u012906122/article/details/103592520