Sort an array when two halves are sorted | Merge two sorted halves of Array into single sorted array ; Temp Array store sorted resultant array ; First Find the point where array is divide into two half ; If Given array is all - ready sorted ; Merge two sorted arrays in single sorted array ; Copy the remaining elements of A [ i to half_ ! ] ; Copy the remaining elements of A [ half_ ! to n ] ; Driver code ; Print sorted Array
function mergeTwoHalf ( A , n ) { let temp = new Array ( n ) ; temp . fill ( 0 ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { half_i = i + 1 ; break ; } } if ( half_i == 0 ) return ; let i = 0 , j = half_i , k = 0 ; while ( i < half_i && j < n ) { if ( A [ i ] < A [ j ] ) temp [ k ++ ] = A [ i ++ ] ; else temp [ k ++ ] = A [ j ++ ] ; } while ( i < half_i ) temp [ k ++ ] = A [ i ++ ] ; while ( j < n ) temp [ k ++ ] = A [ j ++ ] ; for ( let i = 0 ; i < n ; i ++ ) A [ i ] = temp [ i ] ; } let A = [ 2 , 3 , 8 , - 1 , 7 , 10 ] ; let n = A . length ; mergeTwoHalf ( A , n ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( A [ i ] + " " ) ;