1. 程式人生 > >遞迴基礎練習之插入排序的遞迴形式

遞迴基礎練習之插入排序的遞迴形式

遞迴基礎練習之插入排序的遞迴形式

遞迴寫法

首先確定insertSort的巨集觀語義對以陣列的0至第n索引項進行插入排序

假設要呼叫insertSort(arr, n),可以得到規模更小的子問題
1.對陣列的0至第n - 1索引項進行插入排序
2.將陣列的第n索引項插入到有序陣列中

聚焦函式的巨集觀語義,可以更好地寫出遞迴函式。

// 對0至n索引項進行插入排序
	private static void insertSort(int[] arr, int n) {
		if (n == 0) {
			return;
		}

		insertSort(arr, n -
1); int temp = arr[n]; int index = n; while (index > 0 && temp < arr[index - 1]) { arr[index] = arr[index - 1]; index--; } arr[index] = temp; }

非遞迴寫法

	// 對前n項進行排序
	private static void insertSort(int[] arr, int n) {
		for (int unsort = 1; unsort < n; unsort++) {
			int
temp = arr[unsort]; // 出列 int index = unsort; // 標記位 while (index > 0 && temp < arr[index - 1]) { arr[index] = arr[index - 1]; // 右移 index--; } arr[index] = temp; } }