1. 程式人生 > >希爾排序(java)

希爾排序(java)

package cho8;
// 希爾排序

public class ShellSort {
//	排序方法

	public static void sort(long[] arr) {
//		初始化間隔
		int h = 1;
		
//		計算最大間隔
		while(h < arr.length / 3) {
			h = h * 3 + 1;
		}
		while(h > 0) {
//			進行插入排序
			long temp = 0;
			for(int i = h; i < arr.length; i ++ ) {
				temp = arr[i];
				int j = i;
				while(j > h - 1 && arr[j - h] >= temp) {
					arr[j] = arr[j - h];
					j -= h;
				}
				arr[j] = temp;
			}
//			減小間隔
			h = (h - 1) / 3;
		}
	}
}