C語言中可以使用多種排序算法對兩個數組進行排序。以下是其中的一種方法:
int mergeArrays(int arr1[], int n1, int arr2[], int n2, int mergedArray[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j])
mergedArray[k++] = arr1[i++];
else
mergedArray[k++] = arr2[j++];
}
while (i < n1)
mergedArray[k++] = arr1[i++];
while (j < n2)
mergedArray[k++] = arr2[j++];
return k; // 返回新數組的長度
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void splitArray(int mergedArray[], int n, int arr1[], int *n1, int arr2[], int *n2) {
*n1 = n / 2;
*n2 = n - *n1;
for (int i = 0; i < *n1; i++)
arr1[i] = mergedArray[i];
for (int i = 0; i < *n2; i++)
arr2[i] = mergedArray[*n1 + i];
}
最后,可以按照以下步驟來對兩個數組進行排序:
int main() {
int arr1[] = {4, 2, 6, 1, 5};
int arr2[] = {9, 7, 3, 8};
int n1 = sizeof(arr1) / sizeof(arr1[0]);
int n2 = sizeof(arr2) / sizeof(arr2[0]);
int mergedArray[n1 + n2];
int mergedArraySize = mergeArrays(arr1, n1, arr2, n2, mergedArray);
bubbleSort(mergedArray, mergedArraySize);
int sortedArr1[n1];
int n1Sorted, sortedArr2[n2];
int n2Sorted;
splitArray(mergedArray, mergedArraySize, sortedArr1, &n1Sorted, sortedArr2, &n2Sorted);
// 輸出排序后的數組
printf("Sorted Array 1: ");
for (int i = 0; i < n1Sorted; i++)
printf("%d ", sortedArr1[i]);
printf("\nSorted Array 2: ");
for (int i = 0; i < n2Sorted; i++)
printf("%d ", sortedArr2[i]);
return 0;
}
請注意,上述代碼只是示例,您可以根據自己的需求進行修改和優化。