This is a program to eliminate duplicate elements from an array. This program can be done using two techniques - using a second array and without using any separate array.
Program using a second array
import java.io.*;
class String1
{
int i,j,x=0,n;
int a[],a1[];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show() throws Exception
{
System.out.println("How many Elements You Want to Store?:");
n=Integer.parseInt(br.readLine());
a=new int[n];
a1=new int[n];
for(i=0; i < n;i++)
{
System.out.print("\nEnter Element:");
a[i]=Integer.parseInt(br.readLine());
}
for(i=0;i< n;i++)
{
if(i==0)
a1[x++]=a[i];
else
{
for(j=0;j< x;j++)
{
if(a1[j]==a[i])
break;
}
if(j==x)
a1[x++]=a[i];
}
System.out.println("\n\nOriginal Elements in the array:");
for(i=0;i< n;i++)
System.out.print(" "+a[i]);
System.out.println("\n\nElements in the array after removing duplicates:");
for(i=0;i< x;i++)
System.out.print(" "+a1[i]);
}
{
String1 ob=new String1();
ob.show();
}
}
Sample Input Output:
How many Elements You Want to Store?:
10
Enter Element:22
Enter Element:4
Enter Element:22
Enter Element:4
Enter Element:5
Enter Element:6
Enter Element:5
Enter Element:123
Enter Element:3
Enter Element:44
Original Elements in the array:
22 4 22 4 5 6 5 123 3 44
Elements in the array after removing duplicates:
22 4 5 6 123 3 44
Program Without Using Second Array
import java.io.*;
class String1
{
int i,j,x,n,m;
int a[];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void show() throws Exception
{
System.out.println("How many Elements You Want to Store?:");
n=Integer.parseInt(br.readLine());
a=new int[n];
for(i=0;i< n;i++)
{
System.out.print("\nEnter Element:");
a[i]=Integer.parseInt(br.readLine());
}
System.out.println("\n\nOriginal Elements in the array:");
for(i=0;i< n;i++)
System.out.print(" "+a[i]);
for(i=0;i< n-1;i++)
{
for(j=i+1;j< n;j++)
{
if(a[i]>a[j])
{
x=a[i];
a[i]=a[j];
a[j]=x;
}
}
}
m=n;
for(i=1;i< m;i++)
{
x=a[i-1];
if(x==a[i])
{
for(j=i-1;j< n-1;j++)
{
a[j]=a[j+1];
}
x=a[i];
m--;
i--;
}
}
System.out.println("\n\nElements in the array after removing duplicates:");
for(i=0;i< m;i++)
System.out.print(" "+a[i]);
}
public static void main(String args[])throws Exception
{
String1 ob=new String1();
ob.show();
}
}
Sample Input Output
How many Elements You Want to Store?:
10
Enter Element:22
Enter Element:33
Enter Element:44
Enter Element:22
Enter Element:33
Enter Element:44
Enter Element:6
Enter Element:7
Enter Element:8
Enter Element:9
Original Elements in the array:
22 33 44 22 33 44 6 7 8 9
Elements in the array after removing duplicates:
6 7 8 9 22 33 44
No comments:
Post a Comment