以下是C函式 merge 的一種可能的實現方式。此函式會合併兩個嚴格遞減的正整數陣列 a 和 b,將合併的結果按照遞減順序存入陣列 out,同時排除任何重複的數值。
c
#include <stdio.h>
void merge(int a[], int b[], int out[]) {
int i = 0, j = 0, k = 0;
// Merge the arrays until one is exhausted, skipping duplicates.
while (a[i] != 0 && b[j] != 0) {
if (a[i] > b[j]) {
out[k++] = a[i++];
} else if (a[i] < b[j]) {
out[k++] = b[j++];
} else {
out[k++] = a[i++];
j++;
}
}
// If any elements remain in a, add them to out.
while (a[i] != 0) {
out[k++] = a[i++];
}
// If any elements remain in b, add them to out.
while (b[j] != 0) {
out[k++] = b[j++];
}
// Set the last element to 0 to mark the end of the array.
out[k] = 0;
}
int main() {
int a[] = {128, 34, 23, 17, 10, 0};
int b[] = {1352, 127, 34, 23, 17, 9, 0};
int out[20]; // Make sure this array is large enough to hold all unique elements from a and b.
merge(a, b, out);
// Print the merged array.
for (int i = 0; out[i] != 0; i++) {
printf("%d, ", out[i]);
}
printf("0\n"); // Print the terminating 0.
return 0;
}
此程式確保 out 陣列足夠大,能夠存儲從 a 和 b 合併後的所有唯一元素。在 merge 函式中,我們使用三個索引 i、j 和 k 分別追蹤 a、b 和 out 陣列。我們循環比較 a[i] 和 b[j],並根據大小將較大的元素放入 out[k],如果發現相等的元素,則只取一次放入 out,並同時增加 i 和 j。當其中一個陣列遍歷完畢,則將另一個陣列剩餘的元素添加到 out 陣列。最後,我們將 out 陣列的最後一個元素設置為 0 以表示陣列的結束。