Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging arrays in java [closed]

Tags:

java

arrays

merge

Let's say you have three String arrays for example:

array1: as,hi,ji

array2: fo,gl

array3: gt,my,wx,zq

As you can see, the individual arrays are sorted. How would you merge them, with the merged array also being sorted? I know you can first write a method to merge a pair of them, then merge the final one with this new one. Mostly I am just confused if you should first merge then sort or vice versa. Would merge sort be useful?


1 Answers

I would use something like

public static String[] join(String[]... sas) {
    String[] result = new String[0];
    for (String[] sa : sas) {
        result = Arrays.copyOf(result, result.length + sa.length);
        System.arraycopy(sa, 0, result, result.length - sa.length, sa.length);
    }
    return result;
}

and then

String[] s = join(s1, s2, s3);
Arrays.sort(s);

Maybe there is any external library handling this.

Related the efectivity, sorting the array has complexity ~ N * log N (merge-sort) which is worse than copying (~ N), so the better way is to unite the array and sort once than sort each particular merge. Java class Arrays uses the merge-sort internally.

like image 199
Mike Avatar answered Jan 25 '26 03:01

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!