fork(1) download
  1. import java.util.Arrays;
  2. /**
  3.  * Intersection and Union of Arrays
  4.  * @author Prateek
  5.  */
  6. class IntersectionAndUnion {
  7.  
  8. private int[] arr1;
  9. private int[] arr2;
  10.  
  11. public IntersectionAndUnion(int[] arr1, int[] arr2) {
  12. this.arr1 =arr1;
  13. this.arr2 =arr2;
  14. Arrays.sort(arr1);
  15. Arrays.sort(arr2);
  16. }
  17.  
  18. public static void main(String[] args) {
  19. int[] arr1={7, 5, 4, 3, 1};
  20. int[] arr2= {2, 3, 5, 6};
  21.  
  22. IntersectionAndUnion obj=new IntersectionAndUnion(arr1 , arr2);
  23.  
  24. System.out.println("Union List: ");
  25. obj.union();
  26.  
  27. System.out.println("Intersection List: ");
  28. obj.intersection();
  29. }
  30.  
  31. /**
  32. * Union Of arrays
  33. */
  34. public void union() {
  35. int i=0,j=0;
  36. while(i < arr1.length && j < arr2.length)
  37. {
  38. if(arr1[i] < arr2[j])
  39. System.out.print(arr1[i++]);
  40. else if(arr1[i] > arr2[j])
  41. System.out.print(arr2[j++]);
  42. else{
  43. System.out.print(arr1[i++]);
  44. j++;
  45. }
  46. System.out.print("\t");
  47. }
  48.  
  49. if(arr2.length > arr1.length)
  50. for(;j<arr2.length;System.out.println(arr2[j]),j++);
  51. else if(arr2.length < arr1.length)
  52. for( ; i<arr1.length;System.out.println(arr1[i]),i++);
  53. }
  54.  
  55. /**
  56. * Intersection of Arrays
  57. */
  58. public void intersection() {
  59. int i=0;
  60. int j=0;
  61. while(i < arr1.length && j < arr2.length)
  62. {
  63. if(arr1[i] < arr2[j])
  64. i++;
  65. else if(arr1[i] > arr2[j])
  66. j++;
  67. else
  68. {
  69. System.out.print(arr1[i++] + "\t");
  70. j++;
  71. }
  72. }
  73. }
  74. }
  75.  
Success #stdin #stdout 0.07s 381248KB
stdin
Standard input is empty
stdout
Union List: 
1	2	3	4	5	6	7
Intersection List: 
3	5