testzuser
testzuser

Reputation: 157

how to merge two sorted arrays of same size?

1st array: {3,5,6,9,12,14,18,20,25,28}
2nd array: {30,32,34,36,38,40,42,44,46,48}

Sample Output:

{3,5,6,9,12,14,18,20,25,28,30,32,34,36,38,40,42,44,46,48}

I have to merge 1st array into second array. 2nd array has space to accomadate all values

Upvotes: 0

Views: 223

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136002

Use System.arraycopy to append a1 to a2

System.arraycopy(a1, 0, a2, a2_len, a1.length);

then Arrays.sort

Upvotes: 1

vach
vach

Reputation: 11377

Whenever i know i need a collection to be sorted, i use a method that will insert new elements in right place, so the collection will never have state when its not sorted... in your case you might be good with adding two into destination collection then use Collections.sort() but you can do sortedInsert() as well... you can create your collection and start addin all items into it using this method, and when you finished you dont need another call to Collections.sort() because collection is always in sorted state... This is handy if you often do single element update and dont want whole collection to be resorted... this will work with much better performance...

Here is what i do for List

/**
   * Inserts the value keeping collection sorted, provided collections shall be sorted with provided
   * comparator
   */
  public static <E> void sortedInsert(List<E> list, E value, Comparator<? super E> comparator) {
    assert Ordering.from(comparator).isOrdered(list);

    if (list.size() == 0) {
      list.add(value);
    } else if (comparator.compare(list.get(0), value) > 0) {
      list.add(0, value);
    } else if (comparator.compare(list.get(list.size() - 1), value) < 0) {
      list.add(list.size(), value);
    } else {
      int i = 0;
      while (comparator.compare(list.get(i), value) < 0) {
        i++;
      }
      list.add(i, value);
    }
  }

Upvotes: 1

AJ.
AJ.

Reputation: 4534

Make a ArrayList object as arrayListObject

ArrayList<Integer> arrayListObject= new ArrayList<>();

Add elements of both arrays in that arrayListObject

Do Collectios.sort(arrayListObject) to sort the elements.

Use

Integer list2[] = new Integer[arrayListObject.size()];
        list2 =  arrayListObject.toArray(list2);

to get the resulted array

Upvotes: 0

Abhishek
Abhishek

Reputation: 7045

Use two pointers/counters, i & j starting from 0 to size of the array. Compare a[i] & b[j] and based on the result shift i or j (similar to merge sort, merging step). If extra space isn't allowed then in worst case (which is true in your input, all the elements in first array is smaller than first element in second array) you might have to shift 2nd array every time you compare elements.

Upvotes: 0

Related Questions