Sort an array with swapping only with a special element is allowed | n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted . ; Print the sorted array when loop reaches the base case ; Else if k > 0 and space is at 0 th index swap each number with space and store index at second last index ; If space is neither start of array nor last element of array and element before it greater than / the element next to space ; First swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 } ; Than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 } ; Wrapper over sortRec . ; Find index of space ( or 999 ) ; Invalid input ; Driver Code
function sortRec ( arr , index , k , n ) { if ( k == 0 ) { for ( let i = 1 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( 999 ) ; return ; } else if ( k > 0 && index == 0 ) { index = n - 2 ; for ( let i = 1 ; i <= index ; i ++ ) { arr [ i - 1 ] = arr [ i ] ; } arr [ index ] = 999 ; } if ( index - 1 >= 0 && index + 1 < n && arr [ index - 1 ] > arr [ index + 1 ] ) { swap ( arr , index , index + 1 ) ; swap ( arr , index - 1 , index + 1 ) ; } else swap ( arr , index , index - 1 ) ; sortRec ( arr , index - 1 , k - 1 , n ) ; } function swap ( arr , i , j ) { let temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } function sort ( arr , n ) { let index = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 999 ) { index = i ; break ; } } if ( index == - 1 ) return ; sortRec ( arr , index , n , n ) ; } let arr = [ 3 , 2 , 999 , 1 ] ; let n = arr . length ; sort ( arr , n ) ;