An in | Javascript implementation of above approach ; A utility function to reverse String str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; Keep the back - up of element at new position ; The main function to transform a String . This function mainly uses cycleLeader ( ) to transform ; Step 1 : Find the largest prefix subarray of the form 3 ^ k + 1 ; Step 2 : Apply cycle leader algorithm for the largest subarrau ; Step 4.1 : Reverse the second half of first subarray ; Step 4.2 : Reverse the first half of second sub - String . ; Step 4.3 Reverse the second half of first sub - String and first half of second sub - String together ; Increase the length of first subarray ; Driver code
let str ; function reverse ( low , high ) { while ( low < high ) { let t = str [ low ] ; str [ low ] = str [ high ] ; str [ high ] = t ; ++ low ; -- high ; } } function cycleLeader ( shift , len ) { let j ; let item ; for ( let i = 1 ; i < len ; i *= 3 ) { j = i ; item = str [ j + shift ] ; do { if ( j % 2 == 1 ) j = Math . floor ( len / 2 ) + Math . floor ( j / 2 ) ; else j = Math . floor ( j / 2 ) ; let t = str [ j + shift ] ; str [ j + shift ] = item ; item = t ; } while ( j != i ) ; } } function moveNumberToSecondHalf ( ) { let k , lenFirst ; let lenRemaining = str . length ; let shift = 0 ; while ( lenRemaining > 0 ) { k = 0 ; while ( Math . pow ( 3 , k ) + 1 <= lenRemaining ) k ++ ; lenFirst = Math . floor ( Math . pow ( 3 , k - 1 ) ) + 1 ; lenRemaining -= lenFirst ; cycleLeader ( shift , lenFirst ) ; reverse ( Math . floor ( shift / 2 ) , shift - 1 ) ; reverse ( shift , shift + Math . floor ( lenFirst / 2 ) - 1 ) ; reverse ( Math . floor ( shift / 2 ) , shift + Math . floor ( lenFirst / 2 ) - 1 ) ; shift += lenFirst ; } } let st = " " ; str = st . split ( " " ) ; moveNumberToSecondHalf ( ) ; document . write ( str . join ( " " ) ) ;