美文网首页
希尔排序,实现从大到小和从小到大排序

希尔排序,实现从大到小和从小到大排序

作者: 小小飞的救赎 | 来源:发表于2018-12-14 16:21 被阅读0次

    实现希尔排序的方法类

    package com.hcc.util;
    
    /**
     * 希尔排序
     * @author hcc
     *
     */
    public class HillSort {
        
        /**
         * 希尔排序:就是直接插入排序的进化版
         * @param arr
         * @param arrLength
         */
        public static void sortingMinToMax(int[] arr,int arrLength) {
            int constant = arrLength/2;
            while(constant > 0) {
                for(int i = constant;i<arrLength;i++) {
                    int j = i - constant;
                    int temp = arr[i];
                    for(;j >= 0 && arr[j] > temp;) {
                        arr[j+constant] = arr[j];
                        j = j - constant;
                    }
                    arr[j+constant] = temp;
                }
                constant = constant/2;
            }   
        }
        
        /**
         * 从大到小
         * @param arr
         * @param length
         */
        public static void sortingMaxToMin(int[] arr,int length) {
            int constant = length/2;
            while(constant > 0) {
                for(int i = constant;i < length;i++) {
                    int temp = arr[i];
                    int j;
                    for(j = i-constant;j >= 0 && arr[j] < temp;) {
                        arr[j+constant] = arr[j];
                        j = j - constant;
                    }
                    arr[j+constant] = temp;
                }
                constant = constant/2;
            }
        }
    }
    

    测试类

    public class Test {
        public static void main(String[] args) {
    
            // 69 65 90 37 92 6 28 54  
            int[] arr = {69,65,70,90,37,92,6,28,54,20};
            System.out.println("原始数据:");
            printSortData(arr);
            System.out.println();       
            System.out.println("希尔排序:");
            hillSortTest(arr);
        }
        
        /**
         * 希尔排序测试方法
         * @param arr
         */
        public static void hillSortTest(int[] arr) {
            //HillSort.sortingMinToMax(arr, arr.length);
            HillSort.sortingMaxToMin(arr, arr.length);
            printSortData(arr);
        }
        
        /**
         * 打印输出方法
         * @param arr
         */
        public static void printSortData(int [] arr) {
            int arrLength = arr.length;
            for(int i = 0;i < arrLength;i++) {
                System.out.print(arr[i]+" ");
            }
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:希尔排序,实现从大到小和从小到大排序

          本文链接:https://www.haomeiwen.com/subject/ceughqtx.html