Sort the numbers according to their sum of digits - GeeksforGeeks

29 Apr, 2022
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 = 6Input: 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++
Python3
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum// of the digits of nint 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 elementsvoid 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 codeint main(){    int arr[] = { 14, 1101, 10, 35, 0 };    int n = sizeof(arr) / sizeof(arr[0]);    sortArr(arr, n);     return 0;}
# Python3 implementation of the approach # Function to return the sum# of the digits of ndef 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 elementsdef 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 codeif __name__ == "__main__" :     arr = [14, 1101, 10, 35, 0];    n = len(arr);    sortArr(arr, n); # This code is contributed by Ryuga
<script> // JavaScript implementation of the approach // Function to return the sum// of the digits of nfunction 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 elementsfunction 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 codelet 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;}
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.
ankthon
prophet1999
shinjanpatra
number-digits
Analysis
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Understanding Time Complexity with Simple Examples
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of different sorting techniques
Bubble Sort
Insertion Sort
Selection Sort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms