Sort an array by left shifting digits of array elements | Function to check if an array is sorted in increasing order or not ; Traverse the array ; Function to sort the array by left shifting digits of array elements ; Stores previous array element ; Traverse the array arr [ ] ; Stores current element ; Stores current element in string format ; Left - shift digits of current element in all possible ways ; Left - shift digits of current element by idx ; If temp greater than or equal to prev and temp less than optEle ; Update arr [ i ] ; Update prev ; If arr is in increasing order ; Otherwise ; Driver Code
function isIncreasing ( arr ) { for ( let i = 0 ; i < arr . length - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } function sortArr ( arr ) { let prev = - 1 ; for ( let i = 0 ; i < arr . length ; i ++ ) { let optEle = arr [ i ] ; let strEle = arr [ i ] . toString ( ) ; for ( let idx = 0 ; idx < strEle . length ; idx ++ ) { let strEle2 = strEle . substr ( idx ) + strEle . substr ( 0 , idx ) ; let temp = parseInt ( strEle2 ) ; if ( temp >= prev && temp < optEle ) optEle = temp ; } arr [ i ] = optEle ; prev = arr [ i ] ; } if ( isIncreasing ( arr ) ) return arr ; else { arr = [ - 1 ] ; return arr ; } } let arr = [ 511 , 321 , 323 , 432 , 433 ] ; let res = sortArr ( arr ) ; for ( let i = 0 ; i < res . length ; i ++ ) document . write ( res [ i ] + " " ) ;