/* Java Program to Merge and Remove Duplicates in an Array */
import java.util.Scanner;
import java.util.*;
public class Mergearray
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int[] array1 = {2,4,5,6,7,9,10,13};
int[] array2 = {2,3,4,5,6,7,8,9,11,15};
int len1 = array1.length;
int len2 = array2.length;
System.out.print("Array1 : ");
for(int i=0; i<len1; i++)
{
System.out.print(array1[i]+ " ");
}
System.out.println();
System.out.print("Array2 : ");
for(int i=0; i<len2; i++)
{
System.out.print(array2[i]+ " ");
}
System.out.println();
int totlen = len1+len2;
int[] array3 = new int[totlen];
for (int i=0; i<len1; i++)
{
array3[i] = array1[i];
}
for (int i=len1,j=0; i<len1+len2; i++,j++)
{
array3[i] = array2[j];
}
System.out.println("Merged Array : ");
for(int i=0; i<totlen; i++)
System.out.print(array3[i]+ " ");
System.out.println();
for (int i = 0; i < totlen; i++)
{
for (int j = i+1; j < totlen; j++)
{
if(array3[i] == array3[j])
{
array3[j] = array3[totlen-1];
totlen--;
j--;
}
}
}
int[] array4 = Arrays.copyOf(array3, totlen);
System.out.println("Array Without Duplicates : ");
Arrays.sort(array4);
System.out.println(Arrays.toString(array4));
}
}
Output :
No comments:
Post a Comment