合并两个有序数组,合并完之后仍有序:
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++;
}
}
网友评论