Reverse words in a given string | Reverse the string ; Check if number of words is even ; Find the middle word ; Starting from the middle start swapping words at jth position and l - 1 - j position ; Check if number of words is odd ; Find the middle word ; Starting from the middle start swapping the words at jth position and l - 1 - j position ; Return the reversed sentence ; Driver code
function RevString ( s , l ) { if ( l % 2 == 0 ) { let j = parseInt ( l / 2 , 10 ) ; while ( j <= l - 1 ) { let temp ; temp = s [ l - j - 1 ] ; s [ l - j - 1 ] = s [ j ] ; s [ j ] = temp ; j += 1 ; } } else { let j = parseInt ( ( l / 2 ) , 10 ) + 1 ; while ( j <= l - 1 ) { let temp ; temp = s [ l - j - 1 ] ; s [ l - j - 1 ] = s [ j ] ; s [ j ] = temp ; j += 1 ; } } let S = s [ 0 ] ; for ( let i = 1 ; i < 9 ; i ++ ) { S = S + " " + s [ i ] ; } return S ; } let s = " " " " ; let words = [ " " , " " , " " , " " , " " , " " , " " , " " , " " ] ; document . write ( RevString ( words , 9 ) ) ;