arvind
arrayq1
1 Answer(s)      5 years and 6 months ago
Posted in : Java Beginners

Write a program to combine 3 sorted arrays into 1 sorted array and remove the duplicate elements in the resultant array

Ads

View Answers

March 1, 2011 at 4:17 PM


Java combine Array:

import java.util.*;

class MergeArray {
        public static int[] merge(int[]... arr) {
                int arrSize = 0;
                for (int[] array : arr) {
                        arrSize += array.length;
                }
                int[] result = new int[arrSize];
                int j = 0;
                for (int[] array : arr) {
                        for (int s : array) {
                                result[j++] = s;
                        }
                }
                return result;
        }

        public static void main(String[] args) {
                int[] array1 = {1,3,2,4,5};
                int[] array2 = {2,3,8,5,6};
                int[] array3 = {4,7,9,6,3};
                Arrays.sort(array1);
                Arrays.sort(array2);
                Arrays.sort(array3);


                int M[] = (int[]) merge(array1, array2, array3);
                System.out.println("Merged Sorted Array is: ");
                Arrays.sort(M);
                for (int i = 0; i < M.length; i++) {
                        System.out.println(M[i]);
                }
                String arr[]=new String[M.length];
                for(int i=0;i<M.length;i++){
                    arr[i]=Integer.toString(M[i]);
                }
                List<String> list = Arrays.asList(arr);
        Set<String> set = new HashSet<String>(list);

        System.out.println("After removing duplicates duplicates: ");
        String[] result = new String[set.size()];
        set.toArray(result);
        Arrays.sort(result);
        for (String s : result) {
            System.out.println(s);
       }
    }
}









Related Tutorials/Questions & Answers:
arrayq1
arrayq1  Write a program to combine 3 sorted arrays into 1 sorted array and remove the duplicate elements in the resultant array

Ads

Advertisement