排序算法总结(5)——希尔排序

来源:互联网 发布:linux查看javahome 编辑:程序博客网 时间:2024/06/01 12:40

希尔排序在插入排序的基础上进行了改进,由于插入排序需要移动即复制数组中的很多元素,降低了执行效率。

希尔排序不必一个一个地移动中间的数据项,通过n-增量排序的方式,改进了执行效率。通过加大插入排序中元素之间的间隔,在这些有间隔的元素中进行插入排序,从而使数据项能大跨度地移动。当这些数据项排过一趟后,再减小数据项的间隔。数据项之间的间隔称为增量,用h表示。

间隔的递归表达式为h=3*h+1.


代码如下:


public class ShellSort {public long[] theArray;public int nElmets;public ShellSort(int max){theArray=new long[max];}public void shSort(){int in,out;long temp;int h=1;while(h<=nElmets/3){h=3*h+1;}while(h>0){for(out=h;out<nElmets;out++){temp=theArray[out];in=out;while((in>h-1)&&(theArray[in-h]>=temp)){theArray[in]=theArray[in-h];in-=h;}theArray[in]=temp;}h=(h-1)/3;}}}


效率:

希尔排序的效率还没人能够从理论上分析,估计它的时间从O(N3/2)到O(N7/6)

0 0
原创粉丝点击