排序之希尔排序

public class Sort {

	public static void prt(int[] a) {
		for (int i : a) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	public static void shell_sort(int[] a) {
		int step = 3;
		int space = 1;
		while (space <= a.length / step) {
			space = step * space + 1;
		}

		while (space > 0) {
			for (int i = 0; i + space < a.length; i++) {
				for (int p = 0; p <= i; p++) {
					if (a[p] > a[i + space]) {
						int tmp = a[i + space];
						for (int j = i + space; j > p; j--) {
							a[j] = a[j - 1];
						}
						a[p] = tmp;
					}
				}
			}
			space = (space - 1) / step;
		}
	}

	public static void main(String[] args) {
		int[] a = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
		prt(a);
		shell_sort(a);
		prt(a);

		// 思路:
		// <1>(space=4)
		// 9, 8, 7, 6, 5, 4, 3, 2, 1
		// ->5, 9, 8, 7, 6, 4, 3, 2, 1
		// ->4, 5, 9, 8, 7, 6, 3, 2, 1
		// ...
		// ->1,2,3,4,5,9,8,7,6
		//		
		// <2>(space=1)
		// 1, 2, 3, 4, 5, 9, 8, 7, 6
		// ->1, 2, 3, 4, 5, 8, 9, 7, 6
		// ->1, 2, 3, 4, 5, 7, 8, 9, 6
		// ->1, 2, 3, 4, 5, 6, 7, 8, 9

		// 运行结果:
		// 9 8 7 6 5 4 3 2 1
		// 1 2 3 4 5 6 7 8 9
	}

}

 

你可能感兴趣的:(J#)