希尔排序

此排序包括升序和降序

以升序为例,先设比较大的步长进行插入排序,然后步长逐步减少,最后保证步长为1的一次插入排序即可

请参考插入排序排序接口与抽象类(java)

package com.bsc.algorithm.sort.shell;

import com.bsc.algorithm.sort.insert.InsertSort;

/**
 * 希尔排序
 * 
 * @author bsc
 *
 */
public class ShellSort<T extends Comparable<T>> extends InsertSort<T> {
    protected void sort(T[] data, int cr) {
        int length = data.length;
        //初始步长为数组长度的一半
        int increment = length / 2;
        while (increment > 0) {
            //进行插入排序
            sort(data, cr, increment);
            //步长每次减少一半(保证最后一次排序步长为1)
            increment = increment / 2;
        }
    }
}

 测试

ArrayGenerator请参考数组数据生成器

package com.bsc.algorithm.sort.test;

import java.util.Arrays;

import com.bsc.algorithm.data.generator.ArrayGenerator;
import com.bsc.algorithm.sort.inf.ISort;
import com.bsc.algorithm.sort.shell.ShellSort;

public class SortTest {

    public static void main(String[] args) {
        ISort<Integer> sortInt = new ShellSort<Integer>();

        Integer[] dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99);
        System.out.println("原序:" + Arrays.toString(dataInt));
        sortInt.sortAsc(dataInt);
        System.out.println("升序:" + Arrays.toString(dataInt) + "\n");

        dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99);
        System.out.println("原序:" + Arrays.toString(dataInt));
        sortInt.sortDesc(dataInt);
        System.out.println("降序:" + Arrays.toString(dataInt) + "\n");

        ISort<Character> sortChar = new ShellSort<Character>();

        Character[] dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90);
        System.out.println("原序:" + Arrays.toString(dataChar));
        sortChar.sortAsc(dataChar);
        System.out.println("升序:" + Arrays.toString(dataChar) + "\n");

        dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90);
        System.out.println("原序:" + Arrays.toString(dataChar));
        sortChar.sortDesc(dataChar);
        System.out.println("降序:" + Arrays.toString(dataChar) + "\n");
    }
}

 

posted @ 2018-06-22 11:13  冰三尺2012  阅读(147)  评论(0编辑  收藏  举报