Union and Intersection of two sorted arrays in C#

Solution 1:

// Include namespace system
using System;
using System.Collections.Generic;

public class GFG
{
  // Function to return the union of two arrays
  internal class Program
{
    static void Main(string[] args)
    {
        int[] arr1 = { 1, 3, 4, 5, 7 };
        int[] arr2 = { 2, 3, 5, 6 };
        int length1 = arr1.Length;
        int length2 = arr2.Length;
        Console.WriteLine("Union");
        for(int i = 0; i < arr1.Length; i++)
        {
            for(int j = 0; j < arr2.Length; j++)
            {
                if(arr1[i] == arr2[j])
                {
                    Console.WriteLine(arr1[i]);
                }
            }
        }

        int[] primaryArr = length1>length2?arr1:arr2;
        int[] secArr = length1<length2? arr1 : arr2;
        Console.WriteLine("Intersect");
        for (int i = 0; i < primaryArr.Length; i++)
        { 
            bool isTaken = true;
            for (int j = 0; j < secArr.Length; j++)
            {
                if (arr1[i] == arr2[j])
                {
                    isTaken = false;
                }
            }
            if (isTaken)
            {
                Console.WriteLine(primaryArr[i]);
            }
        }


        Console.ReadKey();
    }
}
}

Comments

Popular posts from this blog

Input = INDIA, count each char in input string