合并兩個(gè)有序數(shù)組,合并完之后仍有序:
void mergeList(int a[], int aLength, int b[], int bLength, int result[]) {
int aIndex = 0; // 遍歷數(shù)組a的下標(biāo)
int bIndex = 0; // 遍歷數(shù)組b的下標(biāo)
int i = 0; // 記錄當(dāng)前存儲(chǔ)位置
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++;
}
}