Pages

Friday, 2 June 2017

Merge Two arrays without duplicates and sort the array to ascending order

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class MergeArrays {

public static void main(String[] args) {
int a[]={1,2,3,4};
int b[]={10,9,8,7,5,4,0,-6,0,0,0};
int count = 0,temp;

Set<Integer> nodup = new HashSet<Integer>();

for(int i=0;i<a.length;i++){
nodup.add(a[i]);
}
for(int i=0;i<b.length;i++){
nodup.add(b[i]);
}

int f[] = new int[nodup.size()];
int z = 0;

Iterator<Integer> it = nodup.iterator();
while(it.hasNext()){
f[z]=it.next();
z++;
}

for(int l=0;l<f.length;l++){
for(int m=0;m<f.length;m++){
if(f[l]<f[m]){
temp=f[l];
f[l]=f[m];
f[m]=temp;
}
}
}

for(int k=0;k<f.length;k++){
System.out.print(f[k]+" ");
}

}
}

Output:

-6 0 1 2 3 4 5 7 8 9 10 

No comments:

Post a Comment

Code Review

 SOLID Principles S – Single Responsibility Principle There should never be more than one reason for a class to change. O – Open-Closed Prin...