算法代码实现之希尔排序,Java实现

封装成类:

package com.roc.algorithms.sort;

/**
 * 希尔排序
 *
 * @author roc
 */
public class ShellSort {
    //交换数组元素
    private static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void sort(int[] a) {
        int h = 1;
        while (h < a.length / 3) {//寻找合适的间隔h
            h = 3 * h + 1;
        }
        while (h >= 1) {
            //将数组变为间隔h个元素有序
            for (int i = h; i < a.length; i++) {
                //间隔h插入排序
                for (int j = i; j >= h && a[j] < a[j - h]; j -= h) {
                    swap(a, j, j - h);
                }
            }
            h /= 3;
        }
    }
}

测试:

int[] a = {9,0,6,5,8,2,1,7,4,3};
System.out.println(Arrays.toString(a));
ShellSort.sort(a);
System.out.println(Arrays.toString(a));

输出:

[9, 0, 6, 5, 8, 2, 1, 7, 4, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值