Sort first k values in ascending order and remaining n | Function to print half of the array in ascending order and the other half in descending order ; Store the k elements in an array ; Store the remaining n - k elements in an array ; Sorting the array from 0 to k - 1 places ; Sorting the array from k to n places ; Storing the values in the final array arr ; Printing the array ; Driver code
function printOrder ( arr , n , k ) { let len1 = k , len2 = n - k ; let arr1 = new Array ( k ) ; let arr2 = new Array ( n - k ) ; for ( let i = 0 ; i < k ; i ++ ) arr1 [ i ] = arr [ i ] ; for ( let i = k ; i < n ; i ++ ) arr2 [ i - k ] = arr [ i ] ; arr1 . sort ( function ( a , b ) { return a - b ; } ) ; arr2 . sort ( function ( a , b ) { return a - b ; } ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( i < k ) arr [ i ] = arr1 [ i ] ; else { arr [ i ] = arr2 [ len2 - 1 ] ; len2 -- ; } } for ( let i = 0 ; i < n ; i ++ ) { document . write ( arr [ i ] + " " ) ; } } let arr = [ 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 ] ; let k = 4 ; let n = arr . length ; printOrder ( arr , n , k ) ;