Sort the numbers according to their sum of digits | C ++ implementation of the approach ; Function to return the sum of the digits of n ; Function to sort the array according to the sum of the digits of elements ; Vector to store digit sum with respective element ; Inserting digit sum with element in the vector pair ; Quick sort the vector , this will sort the pair according to sum of the digits of elements ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigit ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += n % 10 ; n = n / 10 ; } return sum ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( sumOfDigit ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }