03_希尔排序

package algorithm;

import java.util.*;

/**
 * 希尔排序:本质上是分组的插入排序 
 * 1.首先分组,利用插入排序将组内的元素进行排序好
 * 2.分组粒度不断缩小,每组的元素个数不断增加,还是利用插入排序将组内的元素进行排序
 * 3.直到分组粒度为1的时候,此时变成了插入排序,只有一组,包含所有的元素 4.当粒度编程1的时候,之前的分组排序做好了铺垫,使得大部分的数据已经是有序的了
 * 5.程序中可以看到,当d = 1的时候,就彻底变成了插入排序
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] array = { 5, 6, 9, 8, 7, 1, 3, 2, 4 };
        shellSort(array);
    }

    /**
     * {5, 6, 9, 8, 7, 1, 3, 2, 4} 
     * d = 4 
     * 分组{5,7,4} {6,1} {9,3} {8,2}
     * 0 4 8      1 5    2 6    3 7
     * @param array
     */
    public static void shellSort(int[] array) {
        int len = array.length;
        int d = len;

        while (true) {
            d = d / 2;
            for (int x = 0; x < d; x++) {
                // x 开始取值,然后间隔d取数值,分好组,再用插入排序
                //演示打印分组
                System.out.print("{ ");
                for (int j = x; j < len; j = j + d) {
                    System.out.print(" "+ array[j]);
                }
                System.out.println(" }");
                
                
                for(int i = x + d; i < len; i+=d){
                    int position = i;//记录下当前位置
                    int temp = array[i];//记录下当前位置的值
                    for(int j = i - d;j >= x; j=j-d){
                        if(temp < array[j]){//如果当前值比前面的小,前面的数值就往后移动,要插入的位置position-d
                            array[j+d] = array[j];
                            position = position - d;
                        }else{//移动到正确位置为止
                            break;
                        }
                    }
                    //把要插入的值插入到正确的位置
                    array[position] = temp;
                }
            }
            if (d == 1) {
                break;
            }
        }
        System.out.println(Arrays.toString(array));
    }
}

 

posted @ 2016-06-29 21:15  桃源仙居  阅读(101)  评论(0)    收藏  举报