合并兩個有序數組,合并完之后仍有序:
void mergeList(int a[], int aLength, int b[], int bLength, int result[]) {
int aIndex = 0; // 遍歷數組a的下標
int bIndex = 0; // 遍歷數組b的下標
int i = 0; // 記錄當前存儲位置
while (aIndex < aLength && bIndex < bLength) {
if (a[aIndex] <= b[bIndex]) {
result[i] = a[aIndex];
aIndex++;
} else {
result[i] = b[bIndex];
bIndex++;
}
i++;
}
// a剩余
while (aIndex < aLength) {
result[i] = a[aIndex];
i++;
aIndex++;
}
// b剩余
while (bIndex < bLength) {
result[i] = b[bIndex];
i++;
bIndex++;
}
}