要合并两个数组并排序,可以按照以下步骤进行操作:
下面是一个示例代码:
#include <stdio.h>
void mergeAndSort(int arr1[], int len1, int arr2[], int len2, int result[]) {
int i = 0, j = 0, k = 0;
while (i < len1 && j < len2) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
while (i < len1) {
result[k++] = arr1[i++];
}
while (j < len2) {
result[k++] = arr2[j++];
}
}
int main() {
int arr1[] = {1, 3, 5, 7};
int len1 = sizeof(arr1) / sizeof(arr1[0]);
int arr2[] = {2, 4, 6, 8};
int len2 = sizeof(arr2) / sizeof(arr2[0]);
int result[len1 + len2];
mergeAndSort(arr1, len1, arr2, len2, result);
printf("合并并排序后的数组:");
for (int i = 0; i < len1 + len2; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
输出:
合并并排序后的数组:1 2 3 4 5 6 7 8