## Sunday, January 17, 2016

### Merge two sorted arrays with O(1) extra space - GeeksforGeeks

Merge two sorted arrays with O(1) extra space - GeeksforGeeks
We are given two sorted array. We need to merge these two arrays such that the initial numbers (after complete sorting) are in the first array and the remaining numbers are in the second array. Extra space allowed in O(1).

This task is simple and O(m+n) if we are allowed to use extra space. But it becomes really complicated when extra space is not allowed and doesn’t look possible in less than O(m*n) worst case time.
The idea is to begin from last element of ar2[] and search it in ar1[]. If there is a greater element in ar1[], then we move last element of ar1[] to ar2[]. To keep ar1[] and ar2[] sorted, we need to place last element of ar2[] at correct place in ar1[]. We can use Insertion Sort type of insertion for this. Below is algorithm:
```1) Iterate through every element of ar2[] starting from last
element. Do following for every element ar2[i]
a) Store last element of ar1[i]: last = ar1[i]
b) Loop from last element of ar1[] while element ar1[j] is
smaller than ar2[i].
ar1[j+1] = ar1[j] // Move element one position ahead
j--
c) If any element of ar1[] was moved or (j != m-1)
ar1[j+1] = ar2[i]
ar2[i] = last
```
The worst case time complexity of code/algorithm is O(m*n). The worst case occurs when all elements of ar1[] are greater than all elements of ar2[].
`void` `merge(``int` `ar1[], ``int` `ar2[], ``int` `m, ``int` `n)`
`{`
`    ``// Iterate through all elements of ar2[] starting from`
`    ``// the last element`
`    ``for` `(``int` `i=n-1; i>=0; i--)`
`    ``{`
`        ``/* Find the smallest element greater than ar2[i]. Move all`
`           ``elements one position ahead till the smallest greater`
`           ``element is not found */`
`        ``int` `j, last = ar1[m-1];`
`        ``for` `(j=m-1; j >= 0 && ar1[j] > ar2[i]; j--)`
`            ``ar1[j+1] = ar1[j];`

`        ``// If there was a greater element`
`        ``if` `(j != m-1)`
`        ``{`
`            ``ar1[j+1] = ar2[i];`
`            ``ar2[i] = last;`
`        ``}`
`    ``}`
`}`

#### 1 comment:

1. Hi,

Useful java program. Very well explained. Thanks for sharing.

Cheers,
http://www.flowerbrackets.com/insertion-sort-in-java/