Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if an array element is concatenation of two elements from another array
Next article icon

Merging elements of two different arrays alternatively in third array

Last Updated : 01 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array.

Input : arr1[] = {1, 2, 3, 4, 5, 6}
           arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6}

Input : arr1[] = {1, 2, 3, 4, 5, 6, 7, 8} 
            arr2[] = {11, 22, 33, 44}
Output: {1, 11, 2, 22, 3, 33, 4, 44, 5, 6, 7, 8}

We traverse both given arrays and one by one put their elements into combined array. After one of the arrays is exhausted, we put remaining elements of other array. 

Implementation:

C




// C program to merge two sorted arrays/
#include <stdio.h>
 
// Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
void alternateMerge(int arr1[], int arr2[], int n1, int n2,
                    int arr3[])
{
    int i = 0, j = 0, k = 0;
 
    // Traverse both array
    while (i < n1 && j < n2) {
        arr3[k++] = arr1[i++];
        arr3[k++] = arr2[j++];
    }
 
    // Store remaining elements of first array
    while (i < n1)
        arr3[k++] = arr1[i++];
 
    // Store remaining elements of second array
    while (j < n2)
        arr3[k++] = arr2[j++];
}
 
// Driver code
int main()
{
    int arr1[] = { 1, 3, 5, 7, 9, 11 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
 
    int arr2[] = { 2, 4, 6, 8 };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
 
    int arr3[n1 + n2];
    alternateMerge(arr1, arr2, n1, n2, arr3);
 
    printf("Array after merging\n");
    for (int i = 0; i < n1 + n2; i++)
        printf("%d ",arr3[i]);
 
    return 0;
}
 
 

C++




// C++ program to merge two sorted arrays/
#include <iostream>
using namespace std;
 
// Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
void alternateMerge(int arr1[], int arr2[], int n1, int n2,
                    int arr3[])
{
    int i = 0, j = 0, k = 0;
 
    // Traverse both array
    while (i < n1 && j < n2) {
        arr3[k++] = arr1[i++];
        arr3[k++] = arr2[j++];
    }
 
    // Store remaining elements of first array
    while (i < n1)
        arr3[k++] = arr1[i++];
 
    // Store remaining elements of second array
    while (j < n2)
        arr3[k++] = arr2[j++];
}
 
// Driver code
int main()
{
    int arr1[] = { 1, 3, 5, 7, 9, 11 };
    int n1 = sizeof(arr1) / sizeof(arr1[0]);
 
    int arr2[] = { 2, 4, 6, 8 };
    int n2 = sizeof(arr2) / sizeof(arr2[0]);
 
    int arr3[n1 + n2];
    alternateMerge(arr1, arr2, n1, n2, arr3);
 
    cout << "Array after merging" << endl;
    for (int i = 0; i < n1 + n2; i++)
        cout << arr3[i] << " ";
 
    return 0;
}
 
 

Java




// Java program to merge two sorted arrays
import java.io.*;
 
class GFG {
 
    // Alternatively merge arr1[0..n1-1] and
    // arr2[0..n2-1] into arr3[0..n1+n2-1]
    static void alternateMerge(int arr1[], int arr2[],
                               int n1, int n2, int arr3[])
    {
        int i = 0, j = 0, k = 0;
 
        // Traverse both array
        while (i < n1 && j < n2) {
            arr3[k++] = arr1[i++];
            arr3[k++] = arr2[j++];
        }
 
        // Store remaining elements of first array
        while (i < n1)
            arr3[k++] = arr1[i++];
 
        // Store remaining elements of second array
        while (j < n2)
            arr3[k++] = arr2[j++];
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr1[] = { 1, 3, 5, 7, 9, 11 };
        int n1 = arr1.length;
 
        int arr2[] = { 2, 4, 6, 8 };
        int n2 = arr2.length;
 
        int arr3[] = new int[n1 + n2];
        alternateMerge(arr1, arr2, n1, n2, arr3);
 
        System.out.println("Array after merging");
        for (int i = 0; i < n1 + n2; i++)
            System.out.print(arr3[i] + " ");
    }
}
 
// This code is contributed
// by Nikita Tiwari.
 
 

Python3




# Python3 program to merge two sorted arrays/
 
# Alternatively merge arr1[0..n1-1] and
# arr2[0..n2-1] into arr3[0..n1 + n2-1]
 
 
def alternateMerge(arr1, arr2, n1, n2, arr3):
    i = 0
    j = 0
    k = 0
 
    # Traverse both array
    while (i < n1 and j < n2):
        arr3[k] = arr1[i]
        i += 1
        k += 1
 
        arr3[k] = arr2[j]
        j += 1
        k += 1
 
    # Store remaining elements of first array
    while (i < n1):
        arr3[k] = arr1[i]
        i += 1
        k += 1
 
    # Store remaining elements of second array
    while (j < n2):
        arr3[k] = arr2[j]
        k += 1
        j += 1
 
 
# Driver code
arr1 = [1, 3, 5, 7, 9, 11]
n1 = len(arr1)
 
arr2 = [2, 4, 6, 8]
n2 = len(arr2)
 
arr3 = [0] * (n1 + n2)
alternateMerge(arr1, arr2, n1, n2, arr3)
 
print("Array after merging")
for i in range(0, (n1 + n2)):
    print(arr3[i], end=" ")
 
# This code is contributed by Nikita Tiwari.
 
 

C#




// C# program to merge two sorted arrays
using System;
 
class GFG {
 
    // Alternatively merge arr1[0..n1-1]
    // and arr2[0..n2-1] into arr3[0..n1+n2-1]
    static void alternateMerge(int[] arr1, int[] arr2,
                               int n1, int n2, int[] arr3)
    {
        int i = 0, j = 0, k = 0;
 
        // Traverse both array
        while (i < n1 && j < n2) {
            arr3[k++] = arr1[i++];
            arr3[k++] = arr2[j++];
        }
 
        // Store remaining elements of first array
        while (i < n1)
            arr3[k++] = arr1[i++];
 
        // Store remaining elements of second array
        while (j < n2)
            arr3[k++] = arr2[j++];
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr1 = new int[] { 1, 3, 5, 7, 9, 11 };
        int n1 = arr1.Length;
 
        int[] arr2 = new int[] { 2, 4, 6, 8 };
        int n2 = arr2.Length;
 
        int[] arr3 = new int[n1 + n2];
        alternateMerge(arr1, arr2, n1, n2, arr3);
 
        Console.WriteLine("Array after merging");
        for (int i = 0; i < n1 + n2; i++)
            Console.Write(arr3[i] + " ");
    }
}
 
// This code is contributed by Sam007.
 
 

PHP




<?php
// PHP program to merge two
// sorted arrays
 
// Alternatively merge arr1[0..n1-1]
// and arr2[0..n2-1] into
// arr3[0..n1+n2-1]
function alternateMerge($arr1, $arr2,
                        $n1, $n2)
{
    $i = 0;
    $j = 0;
    $k = 0;
    $arr3 = array();
     
    // Traverse both array
    while ($i < $n1 && $j < $n2)
    {
        $arr3[$k++] = $arr1[$i++];
        $arr3[$k++] = $arr2[$j++];
    }
 
    // Store remaining elements
    // of first array
    while ($i < $n1)
        $arr3[$k++] = $arr1[$i++];
 
    // Store remaining elements
    // of second array
    while($j < $n2)
        $arr3[$k++] = $arr2[$j++];
         
    echo "Array after merging"."\n";
    for ($i = 0; $i < ($n1 + $n2); $i++)
        echo $arr3[$i] ." ";
 
}
 
    // Driver Code
    $arr1 = array(1, 3, 5, 7, 9, 11);
    $n1 = count($arr1);
 
    $arr2 = array(2, 4, 6, 8);
    $n2 = count($arr2);
    alternateMerge($arr1, $arr2, $n1, $n2);
 
// This code is contributed by Sam007
?>
 
 

Javascript




<script>
 
// Javascript program to merge two sorted arrays/
 
// Alternatively merge arr1[0..n1-1] and arr2[0..n2-1]
// into arr3[0..n1+n2-1]
function alternateMerge(arr1, arr2, n1,
                    n2, arr3)
{
    let i = 0, j = 0, k = 0;
 
    // Traverse both array
    while (i<n1 && j <n2)
    {
        arr3[k++] = arr1[i++];
        arr3[k++] = arr2[j++];
    }
 
    // Store remaining elements of first array
    while (i < n1)
        arr3[k++] = arr1[i++];
 
    // Store remaining elements of second array
    while (j < n2)
        arr3[k++] = arr2[j++];
}
 
// Driver code
 
    let arr1 = [1, 3, 5, 7, 9, 11];
    let n1 = arr1.length;
 
    let arr2 = [2, 4, 6, 8];
    let n2 = arr2.length;
 
    let arr3 = new Array(n1+n2);
    alternateMerge(arr1, arr2, n1, n2, arr3);
 
    document.write("Array after merging" + "<br>");
    for (let i=0; i < n1+n2; i++)
        document.write(arr3[i] + " ");
 
// This code is contributed by Mayank Tyagi
 
</script>
 
 
Output
Array after merging 1 2 3 4 5 6 7 8 9 11 

Time Complexity: O(n1 + n2), where n1 and n2 are the sizes of the given two arrays.
Auxiliary Space: O(n1 + n2)



Next Article
Check if an array element is concatenation of two elements from another array

A

Akshat Gupta 1995
Improve
Article Tags :
  • Arrays
  • DSA
  • Java
Practice Tags :
  • Arrays
  • Java

Similar Reads

  • Intersection of Two Sorted Arrays with Distinct Elements
    Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order. Note: Intersection of two arrays can be defined as a set containing distinct common el
    13 min read
  • Check if an array element is concatenation of two elements from another array
    Given two arrays arr[] and brr[] consisting of N and M positive integers respectively, the task is to find all the elements from the array brr[] which are equal to the concatenation of any two elements from the array arr[]. If no such element exists, then print "-1". Examples: Input: arr[] = {2, 34,
    8 min read
  • Intersection of Two Arrays with Distinct Elements
    Given two arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We can return the answer in any order. Note: Intersection of two arrays can be defined as a set containing distinct common elements between the t
    9 min read
  • Check whether an array can be fit into another array rearranging the elements in the array
    Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second
    6 min read
  • Sum of Bitwise AND of each array element with the elements of another array
    Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise AND of each element of arr1[] with the elements of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 2 4 6Explanation:For elements at index 0 in arr1[], Sum = a
    11 min read
  • Add elements of given arrays with given constraints
    Given two integer arrays, add their elements into third array by satisfying following constraints - Addition should be done starting from 0th index of both arrays. Split the sum if it is a not a single digit number and store the digits in adjacent locations in output array. Output array should accom
    15+ min read
  • Median of two Sorted Arrays of Different Sizes
    Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array. This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal s
    15+ min read
  • Count distinct elements after adding each element of First Array with Second Array
    Given two arrays arr1[] and arr2[]. We can generate another array arr3[] by adding each element of the array arr1[] to each element arr2[]. The task is to find the count of distinct element in the array arr3[]. Examples: Input: Arr1[] = {1, 2}, Arr2[] = {3, 4}, MAX = 4 Output: 4 -> 1 5 -> 2 6
    15+ min read
  • Merge an array of size n into another array of size m+n
    There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted. Input: array with m+n elements (mPlusN[]). NA => Value is not filled/availabl
    12 min read
  • Maximize array sum by concatenating corresponding elements of given two arrays
    Given two array A[] and B[] of the same length, the task is to find the maximum array sum that can be formed by joining the corresponding elements of the array in any order. Input: A[] = {1, 2, 3, 4, 5}, B[] = {3, 2, 1, 4, 5} Output: 183 Explanation: Numbers formed by joining the digits of the eleme
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences