Sort an array by left shifting digits of array elements | Java program for the above approach ; 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
import java . util . * ; class GFG { static boolean isIncreasing ( int [ ] arr ) { for ( int i = 0 ; i < arr . length - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } static int [ ] sortArr ( int [ ] arr ) { int prev = - 1 ; for ( int i = 0 ; i < arr . length ; i ++ ) { int optEle = arr [ i ] ; String strEle = String . valueOf ( arr [ i ] ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { String strEle2 = strEle . substring ( idx ) + strEle . substring ( 0 , idx ) ; int temp = Integer . valueOf ( strEle2 ) ; if ( temp >= prev && temp < optEle ) optEle = temp ; } arr [ i ] = optEle ; prev = arr [ i ] ; } if ( isIncreasing ( arr ) ) return arr ; else { return new int [ ] { - 1 } ; } } public static void main ( String [ ] args ) { int [ ] arr = { 511 , 321 , 323 , 432 , 433 } ; int [ ] res = sortArr ( arr ) ; for ( int i = 0 ; i < res . length ; i ++ ) System . out . print ( res [ i ] + " ▁ " ) ; } }