要合并兩個(gè)數(shù)組并排序,可以按照以下步驟進(jìn)行操作:
下面是一個(gè)示例代碼:
#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("合并并排序后的數(shù)組:");
for (int i = 0; i < len1 + len2; i++) {
printf("%d ", result[i]);
}
printf("\n");
return 0;
}
輸出:
合并并排序后的數(shù)組:1 2 3 4 5 6 7 8