Program to Perform the Union of Two Sorted Arrays [C, C++, Python & Java]

Posted in

Program to Perform the Union of Two Sorted Arrays [C, C++, Python & Java]
vinaykhatri

Vinay Khatri
Last updated on October 4, 2023

    This tutorial will help you learn to write a program to perform the union of two sorted arrays. We will ask the user to enter elements for two arrays in ascending order, combine both array elements, and store them in a new array. The new array, a union of user two entered arrays, must be sorted.

    To write this program, you must know the for loop, if...else statements, programming language syntax, and the concept of an array.

    So, let us begin!

    What is the Union of Arrays?

    The union of arrays is the combination of all unique elements from one or more arrays, resulting in a new array with all distinct elements. It removes duplicate values and keeps only distinct values from all arrays.

    For example,

    arr1[] = {2, 3, 6, 7, 1}
    
    arr2[] = {8, 6, 3, 2, 1, 9}
    
    Union = {1, 2, 3, 6, 7, 8, 9}

    C Program to Perform the Union of Two Sorted Arrays

    #include <stdio.h>
    
    int main() {
        int a[50], b[50], c[100];
        int i, k, j, na, nb;
        printf("How many elements do you want to enter in Array A and B?\n");
        scanf("%d", &na);
        scanf("%d", &nb);
        printf("Enter the elements of Array A in ascending order\n");
        for (i = 0; i < na; i++) {
            scanf("%d", &a[i]);
        }
        printf("Now enter the elements of Array B in ascending order\n");
        for (i = 0; i < nb; i++) {
            scanf("%d", &b[i]);
        }
        printf("The Union of the two arrays is:\n");
        k = 0;
        j = 0;
        for (i = 0; i < na + nb; i++) {
            if (k == na) {
                c[i] = b[j];
                j++;
            } else if (j == nb) {
                c[i] = a[k];
                k++;
            } else if (a[k] < b[j]) {
                c[i] = a[k];
                k++;
            } else if (a[k] > b[j]) {
                c[i] = b[j];
                j++;
            } else if (a[k] == b[j]) {
                c[i] = a[k];
                k++;
                j++;
            }
        }
        for (i = 0; i < na + nb; i++) {
            printf("%d ", c[i]);
        }
        return 0;
    }

    Output:

    How many elements do you want to enter in Array A and B?
    5
    7
    Enter the elements of Array A in ascending order
    3
    4
    5
    6
    1
    Now enter the elements of Array B in ascending order
    5
    4
    7
    6
    1
    3
    9
    The Union of the two arrays is:
    3 4 5 4 6 1 7 6 1 3 9 

    C++ Program to Perform the Union of Two Sorted Arrays

    #include<iostream>
    using namespace std;
    
    int main() {
        int a[50], b[50], c[100];
        int i, k, j, na, nb;
        cout << "How many elements do you want to enter in Array A and B?\n";
        cin >> na >> nb;
        cout << "Enter the elements of Array A in ascending order\n";
        for (i = 0; i < na; i++) {
            cin >> a[i];
        }
        cout << "Now enter the elements of Array B in ascending order\n";
        for (i = 0; i < nb; i++) {
            cin >> b[i];
        }
        cout << "The Union of the two arrays is:\n";
        k = 0;
        j = 0;
        for (i = 0; i < na + nb; i++) {
            if (k == na) {
                c[i] = b[j];
                j++;
            } else if (j == nb) {
                c[i] = a[k];
                k++;
            } else if (a[k] < b[j]) {
                c[i] = a[k];
                k++;
            } else if (a[k] > b[j]) {
                c[i] = b[j];
                j++;
            } else if (a[k] == b[j]) {
                c[i] = a[k];
                k++;
                j++;
            }
        }
        for (i = 0; i < na + nb; i++) {
            cout << c[i] << " ";
        }
        return 0;
    }
    

    Output:

    How many elements do you want to enter in Array A and B
    4
    5
    Enter the elements of Array A in ascending order
    3
    4
    7
    9
    Enter the elements of Array B in ascending order
    5
    8
    11
    12
    16
    The Union of the two arrays is
    3 4 5 7 8 9 11 12 16

    Python Program to Perform the Union of Two Sorted Arrays

    a = []
    b = []
    
    na, nb = map(int, input("How many elements do you want to enter in Array A and B?\n").split())
    print("Enter the elements of Array A in ascending order")
    a = [int(input()) for _ in range(na)]
    print("Enter the elements of Array B in ascending order")
    b = [int(input()) for _ in range(nb)]
    
    c = []
    i = j = 0
    
    while i < na and j < nb:
        if a[i] < b[j]:
            c.append(a[i])
            i += 1
        elif a[i] > b[j]:
            c.append(b[j])
            j += 1
        else:
            c.append(a[i])
            i += 1
            j += 1
    
    while i < na:
        c.append(a[i])
        i += 1
    
    while j < nb:
        c.append(b[j])
        j += 1
    
    print("The Union of the two arrays is:")
    for num in c:
        print(num, end=" ")
    

    Output:

    How many elements do you want to enter in Array A and B?
    3 3 
    Enter the elements of Array A in ascending order
    3
    4
    5
    Enter the elements of Array B in ascending order
    1
    2
    3
    The Union of the two arrays is:
    1 2 3 4 5 

    Java Program to Perform the Union of Two Sorted Arrays

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            int a[] = new int[50];
            int b[] = new int[50];
            int c[] = new int[50];
            int i, k, j, na, nb;
            Scanner sc = new Scanner(System.in);
            System.out.println("How many elements do you want to enter in Array A and B?");
            na = sc.nextInt();
            nb = sc.nextInt();
            System.out.println("Enter the elements of Array A in ascending order");
            for (i = 0; i < na; i++) {
                a[i] = sc.nextInt();
            }
            System.out.println("Now enter the elements of Array B in ascending order");
            for (i = 0; i < nb; i++) {
                b[i] = sc.nextInt();
            }
            System.out.println("The Union of the two arrays is:");
            k = 0;
            j = 0;
            for (i = 0; i < na + nb; i++) {
                if (k == na) {
                    c[i] = b[j];
                    j++;
                } else if (j == nb) {
                    c[i] = a[k];
                    k++;
                } else if (a[k] < b[j]) {
                    c[i] = a[k];
                    k++;
                } else if (a[k] > b[j]) {
                    c[i] = b[j];
                    j++;
                } else if (a[k] == b[j]) {
                    c[i] = a[k];
                    k++;
                    j++;
                }
            }
            for (i = 0; i < na + nb; i++) {
                System.out.print(c[i] + " ");
            }
        }
    }

    Output:

    How many elements do you want to enter in Array A and B?
    5
    4
    Enter the elements of Array A in ascending order
    4 
    5
    6
    2
    3
    Now enter the elements of Array B in ascending order
    8
    4
    5
    1
    The Union of the two arrays is:
    4 5 6 2 3 8 4 5 1 

    Conclusion

    There you go! You can now implement a program in C, C++, Python, and Java to perform the union of two sorted arrays. You have to take care of the logic and the use of the for loop to get the correct output.

    Try to implement it on your own. If you encounter any issues, share them via comments. We would be glad to help you.

    People are also reading:

    Leave a Comment on this Post

    0 Comments