栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Java

排序-希尔排序

Java 更新时间:发布时间: 百科书网 趣学号
public class Shell {

    public static void sort(Comparable[] a) {
//        根据数组a的长度,确定增长量h的初值
        int h = 1;
        while (h < a.length / 2) {
            h = 2 * h + 1;
        }
//        希尔排序
        while (h >= 1) {
//排序
//            找到待插入的元素
            for (int i = h; i < a.length; i++){
//                把待插入的元素插入到有序数列中
                for (int j = i; j >= h; j -= h) {

//待插入的元素是a[j],比较a[j]和a[j-h]
                    if (greater(a[j - h], a[j])) {
                        exch(a, j - h, j);
                    } else {
//                        结束循环
                        break;
                    }
                }
        }
//            减小h的值
        h = h / 2;

    }

}


    private static boolean greater(Comparable v, Comparable w) {

        return v.compareTo(w) > 0;
    }


    private static void exch(Comparable[] a, int i, int j) {
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

import java.util.Arrays;

public class ShellTest {
    public static void main(String[] args) {
        Integer[] a={9,1,2,3,5,8,6,7,4,5};
        Shell.sort(a);
        System.out.println(Arrays.toString(a));


    }
}

D:javajdkjdk-14.0.2binjava.exe "-javaagent:D:ideaIC-2021.2.2IDEAIntelliJ IDEA 2020.1.1libidea_rt.jar=53180:D:ideaIC-2021.2.2IDEAIntelliJ IDEA 2020.1.1bin" -Dfile.encoding=UTF-8 -classpath E:ideaProjectitcastoutproductiondata_structure ShellTest
[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]

Process finished with exit code 0
 

转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/602655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号