希尔排序

希尔排序的主要思想:

1.设定若干个步长step

2.将待排序列按照步长增量分为多个序列,比如步长是2,则将待排序列分为(1,3,5,7....)(2,4,6,8....)两个待排序列

3.分别对若干个待排序列进行直接插入排序

4.最后对整个序列做一次直接插入排序

注:直接插入排序在序列有顺序的时候,效率很高

 

public class ShellSort {

    private static SortObj[] sortArray = {
        new SortObj(11,""),new SortObj(9,""),new SortObj(18,""),
        new SortObj(77,""),new SortObj(10,""),new SortObj(9,"+"),new SortObj(6,"")};

    public static void sort() {
        
        // 初始化步长
        int step = sortArray.length / 2 ;
        for(;step > 0;step /= 2) {
            
            // 将序列分为step组进行直接插入排序
            for(int index = 0;index < step;index++) {
                
                for(int indexJ = index + step;indexJ < sortArray.length;indexJ += step) {
                    SortObj obj = sortArray[indexJ];
                    int indexK = indexJ - step;
                    while(indexK >= index && sortArray[indexK].value > obj.value) {
                        sortArray[indexK + step] = sortArray[indexK];
                        indexK -= step;
                    }
                    sortArray[indexK + step] = obj;
                }
                
            }
            
            printSortResult();
        }
    }
    
    public static void printSortResult() {
        
        for(SortObj obj : sortArray) {
            System.out.print(obj.sequence + obj.value + " ");
        }
        System.out.println();
    }
    /**
      * main(这里用一句话描述这个方法的作用)
      * @param args
      */
    public static void main(String[] args) {
        printSortResult();
        sort();
    }

}

 

对于SortObj类,请见 http://happy-tao-cool.iteye.com/blog/2160579

你可能感兴趣的:(希尔排序,排序算法)