1. 程式人生 > >程序員需要掌握的排序算法之希爾排序(最小增量排序)

程序員需要掌握的排序算法之希爾排序(最小增量排序)

直接 info 排序算法 關鍵詞 基本思想 直接插入 下標 減少 print

希爾排序(最小增量排序)

基本思想希爾排序是把記錄按下標的一定增量分組,對每組使用直接插入排序算法排序;隨著增量逐漸減少,每組包含的關鍵詞越來越多,當增量減至1時,整個文件恰被分成一組,算法便終止。

package sortalgorithm;

public class PublicShellSort {

	static void shellSort() {

		int[] sortList = { 1, 3, 2, 4, 10, 7, 8, 9, 5, 6 };
		int n = 1,len = sortList.length;
		for (int step = len / 2; step > 0; step /= 2) {
			for (int i = 0; i < step; i++) {
				for (int j = i + step; j < len; j += step)
					if (sortList[j] < sortList[j - step]) {
						//如果後面的數大於前面的數,則兩兩進行交換
						int temp = sortList[j];
						int k = j - step;
						while (k >= 0 && sortList[k] > temp) {
							sortList[k + step] = sortList[k];
							k -= step;
						}//該循環是位移式
						sortList[k + step] = temp;
					}
			}
			System.out.println("第" + n + "次:");
			for (int m = 0; m < sortList.length; m++) {
				System.out.print(sortList[m] + " ");
			}
			System.out.println();
			n++;
		}
		System.out.println("最終:");
		for (int k = 0; k < sortList.length; k++) {
			System.out.print(sortList[k] + " ");
		}
	}

	public static void main(String[] args) {
		shellSort();
	}
}

  

 運行結果:

技術分享圖片

程序員需要掌握的排序算法之希爾排序(最小增量排序)