0

I need to merge two large string arrays into one and sort them on the whole.

As of I have looked, following are the ways:

  1. Looping

  2. using Array List, such as

    List list = new ArrayList(Arrays.asList(a));
    list.addAll(Arrays.asList(b));
    

Is there any specific way of handling Strings in Android such that it's efficient over Java library utils?

Can any one suggest me efficient way / alternate way of of doing this.

Note : Arrays span up to 8k elements each

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
nmxprime
  • 1,506
  • 3
  • 25
  • 52

1 Answers1

0

Better to use Arrays in your case. Also it'll not take a lot of memory, because you are not coping you Strings.

public <T> T[] merge(T[] a, T[] b) {
    int aLen = a.length;
    int bLen = b.length;

    T[] merged = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
    System.arraycopy(a, 0, merged, 0, aLen);
    System.arraycopy(b, 0, merged, aLen, bLen);

    return merged;
}

Then you need sort it:

String[] mergedArray = merge(a, b);
Arrays.sort(mergedArray);

In this case complexity will be O(n + m) for merged array and (n + m) * log(n + m) for sorting.

In list approach you will have some overhead in case then ArrayList will be extending and conversion from array to collection. O(n) for Arrays.asList(a) and O(n) for adding elements to the list. Then O(m) for Arrays.asList(b) and O(m) for adding elements to the list and also you will have O(m) for expanding list to the need capacity n + m.

Evgeny Kiselev
  • 216
  • 1
  • 8