text: Arrange given numbers to form the smallest number | C ++ implementation of the approach ; Utility function to print the contents of an array ; A comparison function that return true if ' AB ' is smaller than ' BA ' when we concatenate two numbers ' A ' and ' B ' For example , it will return true if we pass 12 and 24 as arguments . This function will be used by sort ( ) function ; Convert first number to string format ; Convert second number to string format ; Check if ' AB ' is smaller or ' BA ' and return bool value since comparison operator ' < = ' returns true or false ; Function to print the arrangement with the smallest value ; If we pass the name of the comparison function it will sort the array according to the compare function ; Print the sorted array ; Driver code
code: #include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] ; } bool compare ( int num1 , int num2 ) { string A = to_string ( num1 ) ; string B = to_string ( num2 ) ; return ( A + B ) <= ( B + A ) ; } void printSmallest ( int N , int arr [ ] ) { sort ( arr , arr + N , compare ) ; printArr ( arr , N ) ; } int main ( ) { int arr [ ] = { 5 , 6 , 2 , 9 , 21 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printSmallest ( N , arr ) ; return 0 ; }