希尔排序(JAVA)

交换不相邻的元素对数组的局部进行排序,最终用插入排序将局部有序的数组排序

读程序写随便写的(为了更明白就在纸上写一写运行过程)

虽然写了这个代码,这个程序理论上应该是没有问题的,但是我到现在还没运行它,每次运行都会出现下面情况

 

(希望以后会对它有更好的理解吧)

 

package sort20171111;

import java.util.Scanner;

public class Shell {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        int []a = new int[5];
        int n;
        Scanner in = new Scanner(System.in);
        n = in.nextInt();
        for(int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }
        
        //希尔排序
        int h = 1;
        while(h < n / 3) {
            h = h * 3 + 1;
        }
        while(h >= 1) {
            for(int i = h; i < n; i++) {
                for(int j = i; j >= h; j = j - h) {
                    if(a[j] < a[j - h]) {
                        int temp;
                        temp = a[j];
                        a[j] = a[j - h];
                        a[j - h] = temp;
                    }
                }
                h = h / 3;
            }
        }
        
        for(int i = 0; i < n; i++) {
            System.out.println(a[i]);
        }
        

    }

}

 

posted on 2017-11-12 13:50  彩虹糖呐  阅读(191)  评论(0)    收藏  举报