Open In App

Sort the numbers according to their sum of digits

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 
Explanation: 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


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
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 = 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
    List<int []> vp= new List<int[]>();
 
    // Inserting digit sum with element in the vector pair
    for (int i = 0; i < n; i++) {
      vp.Add( new int[2] { sumOfDigit(arr[i]), arr[i] } );
    }
 
    // Quick sort the vector, this will sort the pair
    // according to sum of the digits of elements
    vp.Sort((x,y)=>x[0]-y[0]);
 
    // Print the sorted vector content
    for (int i = 0; i < n; i++){
      Console.Write(vp[i][1]+" ");
    }
  }
 
  // Driver code
  public static void Main()
  {
    int[] arr = { 14, 1101, 10, 35, 0 };
    int n = arr.Length;
    sortArr(arr, n);
  }
}
 
// This code is contributed by Utkarsh


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>


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


Output

0 10 1101 14 35 

Time Complexity: O(n log n) for merge sort and heap sort but O(n2) for quick sort
Auxiliary Space: O(n), since n extra space has been taken.

Second Approach: The idea is to use built-in sort function with a comparator function that computes sum for each pair of comparing integers.

Step-by-step approach:

  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.

Below is the implementation of the above approach:

Java




// Java code for the approach
import java.io.*;
import java.util.*;
 
class GFG {
 
public static void main (String[] args)
{
    ArrayList<Integer> arr = new ArrayList<Integer>(
            Arrays.asList(12, 10, 102, 31, 15));
    int n=arr.size();
     
    Collections.sort(arr, new Comparator<Integer>() {
   @Override
   public int compare(final Integer x, Integer y) {
    int tempx=x,tempy=y;
    int sumx=0,sumy=0;
     
    while(tempx!=0)
    {
        sumx+=tempx%10;
        tempx/=10;
    }
     
    while(tempy!=0)
    {
        sumy+=tempy%10;
        tempy/=10;
    }
     
    return sumx-sumy;
   }
 });
     
    for(int x=0;x<n;x++)
    {
        System.out.print(arr.get(x)+" ");
    }
}
}
 
// This code is contributed by Pushpesh Raj.


C#




// C# code for the approach
using System;
using System.Collections.Generic;
 
class GFG {
     
static int Sum_Compare(int x,int y)
{
    int tempx=x,tempy=y;
    int sumx=0,sumy=0;
      
    while(tempx!=0)
    {
        sumx+=tempx%10;
        tempx/=10;
    }
      
    while(tempy!=0)
    {
        sumy+=tempy%10;
        tempy/=10;
    }
      
    return sumx-sumy;
}
 
static public void Main ()
{
    List<int> arr = new List<int>(){12, 10, 102, 31, 15};
    int n=arr.Count;
     
    arr.Sort((x,y)=>Sum_Compare(x,y));
 
    for(int x=0;x<n;x++)
    {
        Console.Write(arr[x]+" ");
    }
}
}
 
// This code is contributed by Aman Kumar.


Javascript




function sumDigits(num) {
    let sum = 0;
    while (num) {
        sum += num % 10;
        num = Math.floor(num / 10);
    }
    return sum;
}
 
function sumCompare(x, y) {
    let sumX = sumDigits(x);
    let sumY = sumDigits(y);
    return sumX - sumY;
}
 
let arr = [12, 10, 102, 31, 15];
arr.sort(sumCompare);
 
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}


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


Output

10 12 102 31 15 

Time Complexity: O(n (log n)2) for merge sort and heap sort but O(n2 log n) for quick sort.
Auxiliary Space: O(1) for quick sort and heap sort but O(n) for merge sort.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads