二、陣列 a 與 b 皆為嚴格遞減正整數陣列,同一陣列中不含重複數值,且它們均以 0 作為 辨識結束元素(即最後一個元素)。請設計 C 函式 merge(int a[], int b[], int out[]), 將兩個嚴格遞減正整數陣列 a 與 b,依由大至小順序進行合併,合併結果 out[]仍為 一個以 0 作為辨識結束元素的嚴格遞減正整數陣列。若兩個陣列中含有相同數值之 元素時,合併內容需不含重複數值。例如:a 內容:128, 34, 23, 17, 10, 0;b 內容: 1352, 127, 34, 23, 17, 9, 0;合併後內容:1352, 128, 127, 34, 23, 17, 10, 9, 0。(25 分)
詳解 (共 1 筆)
詳解
以下是C函式 merge 的一種可能的實現方式。此函式會合併兩個嚴格遞減的正整數陣列 a 和 b,將合併的結果按照遞減順序存入陣列 out,同時排除任何重複的數值。
c
#include <stdio.h>
#include <stdio.h>
void merge(int a[], int b[], int out[]) {
int i = 0, j = 0, k = 0;
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++;
}
}
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++];
}
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++];
}
while (b[j] != 0) {
out[k++] = b[j++];
}
// Set the last element to 0 to mark the end of the array.
out[k] = 0;
}
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.
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.
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 以表示陣列的結束。
}
此程式確保 out 陣列足夠大,能夠存儲從 a 和 b 合併後的所有唯一元素。在 merge 函式中,我們使用三個索引 i、j 和 k 分別追蹤 a、b 和 out 陣列。我們循環比較 a[i] 和 b[j],並根據大小將較大的元素放入 out[k],如果發現相等的元素,則只取一次放入 out,並同時增加 i 和 j。當其中一個陣列遍歷完畢,則將另一個陣列剩餘的元素添加到 out 陣列。最後,我們將 out 陣列的最後一個元素設置為 0 以表示陣列的結束。