【排序算法之】Shell排序和插入排序

看到插入排序眼前就浮现起小时候打扑克牌的情景,插入排序可能是玩牌经常用到的一种排序方法,思想很简单:
对一个将要排序的序列,从第二个元素开始,如果其小于前面元素,则将其插入到前面的元素中去,很自然地,前面的元素要进行后移,不断比较移动直到结束。
插入排序的优点是对于已经很有序的序列效率很高,因为只有很少的移动。希尔排序正是基于此对插入排序进行改进,算法思想是先取小块进行插入排序,然后对基本有序的小块继续插入排序。

public class ShellSort {

    public static void main(String[] args) {
        int[] array = { 49, 38, 65, 97, 76, 13, 27, 49, 55, 4 };
        shellSort(array);

        for (int i = 0; i < array.length; i++)
            System.out.print(array[i] + "  ");
    }

    public static void shellSort(int[] arr) {
        int length = arr.length;
        int d = length;
        int times = 0;
        while (true) {
            d = d / 2;
            for (int i = 0; i < d; i++)
                for (int j = i; j < length; j = j + d) {
                    int k;
                    int temp = arr[j];
                    for (k = j - d; k >= 0 && temp < arr[k]; k = k - d) {
                        arr[k + d] = arr[k];
                    }
                    arr[k+d] = temp;
                }
            times++;
            System.out.println("第" + times + "趟排序结果:");
            for (int i = 0; i < arr.length; i++)
                System.out.print(arr[i] + "  ");
            System.out.println();
            if (d == 1)
                break;

        }
    }
}

最后打印结果为:
第1趟排序结果:
13 27 49 55 4 49 38 65 97 76
第2趟排序结果:
4 27 13 49 38 55 49 65 97 76
第3趟排序结果:
4 13 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值