Sort an array by left shifting digits of array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isIncreasing ( vector < int > arr ) { for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } vector < int > sortArr ( vector < int > arr ) { int prev = -1 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int optEle = arr [ i ] ; string strEle = to_string ( arr [ i ] ) ; for ( int idx = 0 ; idx < strEle . size ( ) ; idx ++ ) { string strEle2 = strEle . substr ( idx ) + strEle . substr ( 0 , idx ) ; int temp = stoi ( strEle2 ) ; if ( temp >= prev && temp < optEle ) optEle = temp ; } arr [ i ] = optEle ; prev = arr [ i ] ; } if ( isIncreasing ( arr ) ) return arr ; else { arr = { -1 } ; return arr ; } } int main ( ) { vector < int > arr = { 511 , 321 , 323 , 432 , 433 } ; vector < int > res = sortArr ( arr ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; return 0 ; }