Sort the numbers according to their sum of digits
Given an array arr[] of N non-negative integers, the task is to sort these integers according to sum of their digits.
Examples:
Input: arr[] = {12, 10, 102, 31, 15}
Output: 10 12 102 31 15
10 => 1 + 0 = 1
12 => 1 + 2 = 3
102 => 1 + 0 + 2 = 3
31 => 3 + 1= 4
15 => 1 + 5 = 6
Input: arr[] = {14, 1101, 10, 35, 0}
Output: 0 10 1101 14 35
First Approach: The idea is to store each element with its sum of digits in a vector pair and then sort all the elements of the vector according to the digit sums stored. Finally, print the elements in order.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the sum // of the digits of n int sumOfDigit( int n) { int sum = 0; while (n > 0) { sum += n % 10; n = n / 10; } return sum; } // Function to sort the array according to // the sum of the digits of elements void sortArr( int arr[], int n) { // Vector to store digit sum with respective element vector<pair< int , int > > vp; // Inserting digit sum with element in the vector pair for ( int i = 0; i < n; i++) { vp.push_back(make_pair(sumOfDigit(arr[i]), arr[i])); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements sort(vp.begin(), vp.end()); // Print the sorted vector content for ( int i = 0; i < vp.size(); i++) cout << vp[i].second << " " ; } // Driver code int main() { int arr[] = { 14, 1101, 10, 35, 0 }; int n = sizeof (arr) / sizeof (arr[0]); sortArr(arr, n); return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class GFG { // Function to return the sum // of the digits of n static int sumOfDigit( int n) { int sum = 0 ; while (n > 0 ) { sum += n % 10 ; n = Math.floorDiv(n , 10 ); } return sum; } // Function to sort the array according to // the sum of the digits of elements static void sortArr( int [] arr, int n) { // Vector to store digit sum with respective element ArrayList<ArrayList<Integer>> vp = new ArrayList<ArrayList<Integer>>(); // Inserting digit sum with element in the vector pair for ( int i = 0 ; i < n; i++) { ArrayList<Integer>temp = new ArrayList<Integer>(); temp.add(sumOfDigit(arr[i])); temp.add(arr[i]); vp.add(temp); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements Collections.sort(vp, new Comparator<ArrayList<Integer>>(){ @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { return o1.get( 0 ) - o2.get( 0 ); } }); // Print the sorted vector content for ( int i = 0 ; i < vp.size(); i++){ System.out.printf( "%d " ,vp.get(i).get( 1 )); } } // Driver code public static void main(String args[]) { int [] arr = { 14 , 1101 , 10 , 35 , 0 }; int n = arr.length; sortArr(arr, n); } } // This code is contributed by shinjanpatra |
Python3
# Python3 implementation of the approach # Function to return the sum # of the digits of n def sumOfDigit(n) : sum = 0 ; while (n > 0 ) : sum + = n % 10 ; n = n / / 10 ; return sum ; # Function to sort the array according to # the sum of the digits of elements def sortArr(arr, n) : # Vector to store digit sum with # respective element vp = []; # Inserting digit sum with element # in the vector pair for i in range (n) : vp.append([sumOfDigit(arr[i]), arr[i]]); # Quick sort the vector, this will # sort the pair according to sum # of the digits of elements vp.sort() # Print the sorted vector content for i in range ( len (vp)) : print (vp[i][ 1 ], end = " " ); # Driver code if __name__ = = "__main__" : arr = [ 14 , 1101 , 10 , 35 , 0 ]; n = len (arr); sortArr(arr, n); # This code is contributed by Ryuga |
Javascript
<script> // JavaScript implementation of the approach // Function to return the sum // of the digits of n function sumOfDigit(n) { let sum = 0; while (n > 0) { sum += n % 10; n = Math.floor(n / 10); } return sum; } // Function to sort the array according to // the sum of the digits of elements function sortArr(arr, n) { // Vector to store digit sum with respective element let vp = []; // Inserting digit sum with element in the vector pair for (let i = 0; i < n; i++) { vp.push([sumOfDigit(arr[i]), arr[i]]); } // Quick sort the vector, this will sort the pair // according to sum of the digits of elements vp.sort(); // Print the sorted vector content for (let i = 0; i < vp.length; i++) document.write(vp[i][1], " " ); } // Driver code let arr = [ 14, 1101, 10, 35, 0 ]; let n = arr.length; sortArr(arr, n); // This code is contributed by shinjanpatra </script> |
0 10 1101 14 35
Time Complexity: O(n log n) for merge sort and heap sort but O(n^2) for quick sort
Auxiliary Space: O(n)
Second Approach: The idea is to use built-in sort function with a comparator function that computes sum for each pair of comparing integers.
1. Pass the array arr into sort function with Sum_Compare comparator function.
2. Inside Sum_Compare function, calculate sum of digits of both numbers x and y as sumx and sumy by taking modulus by 10 and then dividing it by 10.
3. return whether sumx is less than sumy.
C++14
#include <bits/stdc++.h> using namespace std; bool Sum_Compare( int x, int y) { int tempx=x,tempy=y; int sumx=0,sumy=0; while (tempx) { sumx+=tempx%10; tempx/=10; } while (tempy) { sumy+=tempy%10; tempy/=10; } return sumx<sumy; } int main() { int arr[]={12, 10, 102, 31, 15}; int n= sizeof (arr)/ sizeof (arr[0]); sort(arr,arr+n,Sum_Compare); for ( auto & x:arr) cout<<x<< " " ; return 0; } |
Python3
# Python3 code for the approach from functools import cmp_to_key def Sum_Compare(x, y): tempx,tempy = x,y sumx,sumy = 0 , 0 while (tempx > 0 ): sumx + = tempx % 10 tempx = tempx / / 10 while (tempy > 0 ): sumy + = tempy % 10 tempy = tempy / / 10 return sumx - sumy arr = [ 12 , 10 , 102 , 31 , 15 ] n = len (arr) arr.sort(key = cmp_to_key(Sum_Compare)) for x in arr: print (x,end = " " ) # This code is contributed by shinjanpatra |
Javascript
<script> // JavaScript code for the approach function Sum_Compare(x, y) { let tempx = x,tempy = y; let sumx = 0,sumy = 0; while (tempx) { sumx += tempx % 10; tempx /= 10; } while (tempy) { sumy += tempy % 10; tempy /= 10; } return sumx<sumy; } let arr = [12, 10, 102, 31, 15]; let n = arr.length; arr.sort(Sum_Compare); for (let x of arr) document.writea(x, " " ); // This code is contributed by shinjanpatra </script> |
10 12 102 31 15
Time Complexity: O(n (log n)^2) for merge sort and heap sort but O(n^2 log n) for quick sort.
Auxiliary Space: O(1) for quick sort and heap sort but O(n) for merge sort.