Donald Shell 希尔排序

来源:互联网 发布:学校电脑控制软件 编辑:程序博客网 时间:2024/05/17 02:39

该算法号称是一种冲破二次时间屏障的算法,它通过比较相距一定间隔的元素来工作,每一趟比较所用的距离随着算法的进行而减小,直到只比较相邻一趟的元素为止,

由于增量一直在减小,因此这个排序也称作缩减增量排序.

如果使用增量n,则在使用n一趟排序之后,对于第i个元素,有a[i]<=a[i+n],所有相隔n个位置的元素都是被排序的.

code:

<span style="font-size:18px;">public class TestShellSort {public static void main(String[] args){int[] x = {81,94,11,96,12,35,17,95,28,58,41,75,15};shellSort(x);for(int i: x){System.out.print(i+ " ");}}public static void shellSort(int[] a){int j;int index =0;for(int gap = a.length/2;gap>0;gap/=2){for(int i=gap;i<a.length;i++){int tmp = a[i];for(j=i;j>=gap&&tmp<a[j-gap];j-=gap){a[j] = a[j-gap];}a[j] = tmp;}for(int m : a){System.out.print(m+" ");}++index;System.out.println("the increment times : " + index + " increment size : "+ gap);}}}</span>
输出:

<span style="font-size:18px;">15 94 11 58 12 35 17 95 28 96 41 75 81 the increment times : 1 increment size : 615 12 11 17 41 28 58 94 35 81 95 75 96 the increment times : 2 increment size : 311 12 15 17 28 35 41 58 75 81 94 95 96 the increment times : 3 increment size : 111 12 15 17 28 35 41 58 75 81 94 95 96 </span>



0 0
原创粉丝点击