Efficiently merging two sorted arrays with O ( 1 ) extra space |  ; Find maximum element of both array ; Increment one two avoid collision of 0 and maximum element of array in modulo operation ; Recover back original element to compare ; Update element by adding multiplication with new number ; Update element by adding multiplication with new number ; Process those elements which are left in array a ; Process those elements which are left in array a ; Finally update elements by dividing with maximum element ; Finally update elements by dividing with maximum element ; Driver code ; Length of a ; length of b ; Function Call
using System ; public class GFG { static void mergeArray ( int [ ] a , int [ ] b , int n , int m ) { int mx = 0 ; for ( int I = 0 ; I < n ; I ++ ) { mx = Math . Max ( mx , a [ I ] ) ; } for ( int I = 0 ; I < m ; I ++ ) { mx = Math . Max ( mx , b [ I ] ) ; } mx ++ ; int i = 0 , j = 0 , k = 0 ; while ( i < n && j < m && k < ( n + m ) ) { int e1 = a [ i ] % mx ; int e2 = b [ j ] % mx ; if ( e1 <= e2 ) { if ( k < n ) a [ k ] += ( e1 * mx ) ; else b [ k - n ] += ( e1 * mx ) ; i ++ ; k ++ ; } else { if ( k < n ) a [ k ] += ( e2 * mx ) ; else b [ k - n ] += ( e2 * mx ) ; j ++ ; k ++ ; } } while ( i < n ) { int el = a [ i ] % mx ; if ( k < n ) a [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; i ++ ; k ++ ; } while ( j < m ) { int el = b [ j ] % mx ; if ( k < n ) b [ k ] += ( el * mx ) ; else b [ k - n ] += ( el * mx ) ; j ++ ; k ++ ; } for ( int In = 0 ; In < n ; In ++ ) a [ In ] = a [ In ] / mx ; for ( int In = 0 ; In < m ; In ++ ) b [ In ] = b [ In ] / mx ; return ; } static public void Main ( ) { int [ ] a = { 3 , 5 , 6 , 8 , 12 } ; int [ ] b = { 1 , 4 , 9 , 13 } ; int n = a . Length ; int m = b . Length ; mergeArray ( a , b , n , m ) ; Console . Write ( " First ▁ array ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) Console . Write ( a [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; Console . Write ( " Second ▁ array ▁ : ▁ " ) ; for ( int i = 0 ; i < m ; i ++ ) Console . Write ( b [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } }