union of two array

Write a program to union two arrays


import java.util.Scanner;
import java.util.Arrays;
public class UnionTwoArray {
public static void main(String[] args) {
System.out.println("For First Array : ");
int[] arr1=inputArray();
System.out.println("For Second Array : ");
int[] arr2=inputArray();
int[] arr3=mergeSort(arr1, arr2);
int []arr4=removeDuplicates(arr3);
displayArray(arr4);
}
static int[] inputArray() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array : ");
int n=sc.nextInt();
int count=0;
int arr[]=new int[n];
System.out.println("enter value in array : ");
for (int i=0; i<n; i++) {
arr[i]=sc.nextInt();
}
return arr;
}
static int[] mergeSort(int a[],int b[]) {
int c[]=new int[a.length+b.length];
int i=0,j=0,k=0;
while(i<a.length && j<a.length) {
if(a[i]<b[j] || a[i]==b[j]) {
c[k++]=a[i++];
}
else if(a[i]!=b[j]) {
c[k++]=b[j++];
}
}while(i<a.length) {
c[k++]=a[i++];
}
while(j<b.length) {
c[k++]=b[j++];
}
return c;
}
static int[] removeDuplicates(int []arr){
   int dup=countDuplicate(arr);
int [] k = new int[arr.length-dup];
    k[0]=arr[0];
    int m =1;
    for(int i=1;i<arr.length;++i){
        if(arr[i]!=arr[i-1]){
            k[m]=arr[i];
            ++m;
        }
    }
    return k;
static void displayArray(int arr[]) {
System.out.println("Array is :\n");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if(i!=arr.length-1)
System.out.print(",");
}
}
static int countDuplicate(int arr[]) {
int count=0;
for(int i=0;i<arr.length;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i]==arr[j])
count ++;
}
} return count;
}
}

Comments

Popular posts from this blog