您的位置:首页 > 运维架构 > Shell

排序算法——希尔排序(Shell Sort)

2017-05-29 18:46 507 查看

排序算法——希尔排序(Shell Sort)

算法简介(Introduction)

Insertion sort shifts elements which are out of order one position. For example, an array 1, 3, 2, 4, 5. Shift 3 to 2. It turns 1, 2, 3, 4, 5. The distance of shift is one position.

Shell sort improves insertion sort by increasing the distance of shift. For example, an array 5, 2, 3, 4, 1. Shift 5 to 1. It turns 1, 2, 3, 4, 5. The distance of shift is 5 positions.

Based on this idea, shell sort divides an array into a few subarrays in which elements are apart from each other for the distance of gap. We sort those subarrays independetly by using insertion sort. After that, reduce gap. Continue to sort new subarrays of new gap. A final round of insertion sort finishes the job.

示例(Example)



The gap is 4. The array is divided into 4 subarrays. they are



Sort each subarray by using insertion sort,



The whole array,



Decease gap to 1. There are 22 subarrays. Each array has only one element.



Use final round of insertion sort,



伪代码(Pseudocode)

function ShellSort(A[0..n-1])
gap ⟵ 1
while 3 * gap + 1 ≤ n do
gap ⟵ 3 * gap + 1
while gap ≥ 1 do
for i ⟵ gap to n do
tmp ⟵ A[i]
j ⟵ i-gap
while j ≥ 0 and A[j] > tmp
j ⟵ j - gap
A[j] ⟵ tmp
gap ⟵ (gap - 1)/3


Gap的变化(The change of gap)

The sequence of change of gap is 1, 4, 13, 40, 121, 364, 1093… and work backwards.

基本属性(Property)

1. In-place? Yes. Only requires a constant amount O(1) of additional memory space.

2. Stable? No. For example, an array



After shell sort,



The relative order of two 88 has been changed.

时间复杂度(Time Complexity)

Conjectured to be O(n^1.25).

The algorithm is extremely hard to analyse.

(If you’re interested, please see https://en.wikipedia.org/wiki/Shellsort ).

适用情形(Suitable situation)

1. Linear time for almost-sorted array.

2. Small array (a couple of hundreds elements).

3. Some clever sorting algorithms perform amost-sorting and then let insertion sort take over.

Shell sort is a little bit better than insertion sort.

Java code

public class Sort{
//Shell sort method
public static void shellSort(int [] A){
int gap = 1;
int i,j,tmp;
while(3 * gap + 1 < A.length){
gap = 3 * gap + 1;
}
while(gap >= 1){
for(i = gap; i<A.length; i++){
tmp = A[i];
j = i-gap;
while(j >= 0 && A[j] > tmp){
A[j + gap] = A[j];
j = j - gap;
}
A[j + gap] = tmp;
}
gap = (gap - 1)/3;
}
}

//Test
public static void main(String [] args)
{
int[] A={98,14,55,31,44,83,25,77,47,57,49,52,72,29,64,26,33,89,38,32,94,17};
Sort.shellSort(A);
for(int i=0; i<A.length; i++)
System.out.print(A[i]+" ");
}
}


运行结果(Result)

14 17 25 26 29 31 32 33 38 44 47 49 52 55 57 64 72 77 83 89 94 98


写在最后的话(Postscript)

Shell sort O(n^1.25) is an improvement of insertion sort O(n^2).

Welcome questions always and forever.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: