交替合併兩個不同陣列的元素在 C++ 中的第三個陣列中。


問題陳述

給定兩個陣列,我們需要以這樣的方式合併兩個陣列:組合的陣列具有第一個和第二個陣列的交替元素。如果其中一個數組具有額外的元素,則應在合併陣列的末尾附加這些元素。

arr1[] = {10, 20, 30, 40}
arr2[] = {-10, -20, -30, -40}
result[] = {10, -10, 20, -20, 30, -30, 40, -40}

演算法

1. Traverse both arrays and one by one put elements into result array.
2. If one of the array exhausts then put remaining elements of other array into result array.

示例

#include <iostream>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
void alternateMergedArray(int *arr1, int n1, int *arr2, int n2,int *result){
   int i, j, k;
   i = 0;
   j = 0;
   k = 0;
   while (i < n1 && j < n2) {
      result[k] = arr1[i];
      ++k;
      ++i;
      result[k] = arr2[j];
      ++k;
      ++j;
   }
   while (i < n1) {
      result[k] = arr1[i];
      ++k;
      ++i;
   }
   while (j < n2) {
      result[k] = arr2[j];
      ++k;
      ++j;
   }
}
void displayArray(int *arr, int n){
   for (int i = 0; i < n; ++i) {
      cout << arr[i] << " ";
   }
   cout << endl;
}
int main(){
   int arr1[] = {10, 20, 30, 40};
   int arr2[] = {-10, -20, -30, -40};
   int result[SIZE(arr1) + SIZE(arr2)];
   cout << "First array: " << endl;
   displayArray(arr1, SIZE(arr1));
   cout << "Second array: " << endl;
   displayArray(arr2, SIZE(arr2));
   cout << "Result array: " << endl;
   alternateMergedArray(arr1, SIZE(arr1), arr2, SIZE(arr2),result);
   displayArray(result, SIZE(result));
   return 0;
}

輸出

當您編譯和執行上述程式時。它產生以下輸出 -

First array:
10 20 30 40
Second array:
-10 -20 -30 -40
Result array:
10 -10 20 -20 30 -30 40 -40

更新於:31-Oct-2019

724 閱讀

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告