希尔排序 Java实现

来源:互联网 发布:烟雾视频软件 编辑:程序博客网 时间:2024/05/17 06:20

希尔排序实际上是针对插入排序的一种优化算法。当被插入的元素要移动到数组的开始位置时需要比较的次数相当大,通过改变相邻的元素比较为距离间隔为h的元素比较(h逐渐减小为1)就能减少比较的次数。
代码如下:

public class Tester {    private static final int N = 10;    public static void main(String[] args){        Random random = new Random();        int[] t = new int[N];        for(int i=0;i<N;i++){            t[i]=random.nextInt(80);        }        shellSort(t);        for(int a :t){            System.out.print(a+"\t");        }    }    /*     * 将数组中下标为i与下标为k的数进行交换     */    public static void swap(int[] t,int i,int j){        int temp = t[i];        t[i]=t[j];        t[j]=temp;    }    public static void shellSort(int[] t){        int length = t.length;        int h=1;        while(h<length){h=h*3+1;}        while(h>=1){            for(int i=h;i<length;i++){                //进行插入排序 t[j] t[j-h] t[j-2h]...                for(int j=i;j>=h && t[j]<t[j-h];j-=h){                    swap(t,j,j-h);                }            }            h=h/3;        }    }}
原创粉丝点击