希尔排序——ShellSort

package sort.com;
public class ShellSortFirst {
/**
* 程序入口方法
*/
public static void main(String[] args) {

    int []a={12,6,9,63,-22,0,96,1,7};
     // 计算出h的最大值    
    int h=1;    
    while(h<=a.length/3){

        h=h*3+1;
    }

    //在h的不断变化过程中将原序列分为多个子序列,并对这些子序列分别进行直接插入排序,当h=1时,对所有数据进行最后一次直接插入排序
    while(h>0){
        //利用for循环将序列分为若干个子序列
        for(int i = h; i < a.length; i++){
            //将待排序的数据进行存储
            int temp = a[i];

            /*开始判断子序列的前两个数是否按从小到大排列,若是,则执行for循环的第三个条件语句:i=++,然后继续执行if语句;
                                                       若不是,进入下面循环进行操作*/
            if(a[i] < a[i-h]){

                int j = i-h;

                for( ; j >= 0 && temp <a[j]; j = j - h ){

                    //子序列中较大的数后移h位
                    a[j+h] = a[j];  
                }

                //插入操作,也是真正的赋值操作
                a[j+h] = temp;

            }
        }

        //输出不同h值对应的不同序列
        System.out.println("当h=" + h + "时,序列为" );

        for(int x : a){

            System.out.print(x+",");

            } 
        System.out.println("\n");
        //通过该公式让h不断变化,该公式是固定的
        h = (h-1)/3;
    }

    //遍历完成排序的输出并输出
     System.out.println("最后结果:");
    for(int s : a){

        System.out.print(s+",");
    }
}

}

猜你喜欢

转载自blog.csdn.net/MisterMister/article/details/53819518