Home > Software engineering >  How to merge two integer arrays in ascending order?
How to merge two integer arrays in ascending order?

Time:12-09

How can I merge two arrays in ascending order? I have the code below and I need to merge this array in ascending order, and it should be in a separate method. So in this case the method should return {1, 4, 8, 9, 11, 12, 13}

public class MergingArrays {
    public static void main(String[] args) {
        int [] array1 = {4, 8, 12, 13};
        int [] array2 = {1, 9, 11};
        merge(array1, array2);
    } 
    public static int[] merge(int array1[], int array2[]) {

    }
}

CodePudding user response:

Assuming that you are looking to merge two sorted arrays, you could do it like this.

public static int[] merge(int array1[], int array2[]) {
    int i = 0, j = 0, k = 0;
    int size1 = array1.length;
    int size2 = array2.length;
    int[] result = new int[size1   size2];

    while (i < size1 && j < size2) {
        if (array1[i] < array2[j]) {
            result[k  ] = array1[i  ];
        } else {
            result[k  ] = array2[j  ];
        }
    }

    // Store remaining elements
    while (i < size1) {
        result[k  ] = array1[i  ];
    }

    while (j < size2) {
        result[k  ] = array2[j  ];
    }
    
    return result;

}

CodePudding user response:

public static int[] merge(int[] array1, int[] array2) {
        int totalElements = array1.length   array2.length, array2Index = 0;
        int[] toReturn = new int[totalElements];

        for (int i = 0; i < array1.length; i  ) {
            toReturn[i] = array1[i];
        }
        for (int i = array1.length; i < totalElements; i  ) {
            toReturn[i] = array2[array2Index  ];
        }

        //Manual Ascending Array Sorting
        for (int i = 0; i < totalElements; i  ) {
            for (int j = 0; j < totalElements; j  ) {
                if(toReturn[i] < toReturn[j]) {
                    int temp = toReturn[i];
                    toReturn[i] = toReturn[j];
                    toReturn[j] = temp;
                }
            }
        }
        return toReturn;
    }

CodePudding user response:

You can use apache commons class and the sort function of Collections class

import org.apache.commons.lang.ArrayUtils;
import java.util.Collections;

public class MergingArrays {
    public static void main(String[] args) {
        int [] array1 = {4, 8, 12, 13};
        int [] array2 = {1, 9, 11};
        merge(array1, array2);
    } 
    public static int[] merge(int array1[], int array2[]) {
    return Collections.sort(ArrayUtils.addAll(array1, array2));
    }
}
  • Related