把歸並排序拆成多個檔案來寫,順便練 Makefile 與 gdb,是 C 語言專案化很好的入門題型。
遞推關係:要排序一個大數列,就從中間切成兩半,各自歸並排序,再把兩個已排序的片段依序合併。
Base Case:切到只剩一個元素時不必再排,視為已排序。
實作分成三個檔案:merge.c 負責合併、sort.c 負責遞迴切分、main.c 是測試進入點,另外三個標頭檔放函式原型。
/* This is a merge program.
* Given an integer ARRAY and three numbers which indicate the begin
* and the end of two subarrays, merge the two subarrays to a bigger
* one. The two subarrays are already sorted from small to big.
*/
#include <stdio.h>
#include <stdlib.h>
#include "main.h"
void merge(int *a, int idxa, int idxb, int idxc)
{
int i = idxa, j = idxb, k = 0;
int total = idxc - idxa;
int *temp = (int *)malloc(sizeof(int) * total);
if(temp == NULL)
{
fprintf(stderr, "malloc error in merge function\n");
return;
}
while(i < idxb && j < idxc)
{
if(a[i] < a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
if(i == idxb)
while(j < idxc) temp[k++] = a[j++];
else if(j == idxc)
while(i < idxb) temp[k++] = a[i++];
/* 把暫存陣列拷回原陣列 */
for(i = 0, k = idxa; i < total; k++, i++)
a[k] = temp[i];
free(temp);
}
合併需要額外空間,這裡用 malloc 動態配置並檢查回傳值,用完立刻 free。若改成 C99 的變長陣列 int temp[total],在遞迴深層會累積大量堆疊配置,資料量大時風險不小。
合併完成後必須把暫存內容拷回原陣列,這一步漏掉,上層遞迴拿到的仍是未排序的資料。
用 #ifndef MAIN 包住 merge.c 裡的測試 main,就能在「單檔測試」與「多檔整合」兩種模式下切換,不必來回改程式碼。
target = msort objs = main.o sort.o merge.o $(target): $(objs) gcc -o $(target) $(objs) %.o: %.c gcc -c -g $< clean: rm -f $(objs) $(target)
編譯時加上 -g 才會產生除錯符號。接著用 gdb ./msort 啟動,常用指令是 break merge 設中斷點、run 執行、next 單步(不進入函式)、step 單步(進入函式)、print a[i] 印出變數值、bt 看呼叫堆疊。遞迴演算法用 gdb 觀察每一次呼叫的參數變化,比在程式裡插滿 printf 有效率得多。