Find array with k number of merge sort calls | JavaScript program to find an array that can be sorted with k merge sort calls . ; We make two recursive calls , so reduce k by 2. ; Create an array with values in [ 1 , n ] ; calling unsort function ; Driver code
var k ; function unsort ( l , r , a ) { if ( k < 1 l + 1 == r ) return ; k -= 2 ; var mid = parseInt ( ( l + r ) / 2 ) ; [ a [ mid - 1 ] , a [ mid ] ] = [ a [ mid ] , a [ mid - 1 ] ] ; unsort ( l , mid , a ) ; unsort ( mid , r , a ) ; } function arrayWithKCalls ( n ) { if ( k % 2 == 0 ) { document . write ( " " ) ; return ; } var a = Array ( n + 1 ) ; a [ 0 ] = 1 ; for ( var i = 1 ; i < n ; i ++ ) a [ i ] = i + 1 ; k -- ; unsort ( 0 , n , a ) ; for ( var i = 0 ; i < n ; ++ i ) document . write ( a [ i ] + ' ' ) ; } var n = 10 k = 17 ; arrayWithKCalls ( n ) ;