Merge two sorted arrays with O ( 1 ) extra space | Java program for the above approach ; Function to merge two arrays ; Untill i less than equal to k or j is less tha m ; Sort first array ; Sort second array ; Driver Code
import java . util . Arrays ; import java . util . Collections ; class GFG { static void merge ( int m , int n ) { int i = 0 , j = 0 , k = n - 1 ; while ( i <= k and j < m ) { if ( arr1 [ i ] < arr2 [ j ] ) i ++ ; else { int temp = arr2 [ j ] ; arr2 [ j ] = arr1 [ k ] ; arr1 [ k ] = temp ; j ++ ; k -- ; } } Arrays . sort ( arr1 ) ; Arrays . sort ( arr2 ) ; } public static void main ( String [ ] args ) { int arr1 [ ] = new int [ ] { 1 , 5 , 9 , 10 , 15 , 20 } ; int arr2 [ ] = new int [ ] { 2 , 3 , 8 , 13 } ; merge ( arr1 . length , arr2 . length ) ; System . out . print ( "After Merging  First Array : "); System . out . println ( Arrays . toString ( arr1 ) ) ; System . out . print ( " Second ▁ Array : ▁ " ) ; System . out . println ( Arrays . toString ( arr2 ) ) ; } }