Sort the numbers according to their sum of digits
Last Updated :
11 Mar, 2024
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++
#include <bits/stdc++.h>
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;
}
|
Java
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class GFG
{
static int sumOfDigit( int n)
{
int sum = 0 ;
while (n > 0 ) {
sum += n % 10 ;
n = Math.floorDiv(n , 10 );
}
return sum;
}
static void sortArr( int [] arr, int n)
{
ArrayList<ArrayList<Integer>> vp = new ArrayList<ArrayList<Integer>>();
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);
}
Collections.sort(vp, new Comparator<ArrayList<Integer>>(){
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
return o1.get( 0 ) - o2.get( 0 );
}
});
for ( int i = 0 ; i < vp.size(); i++){
System.out.printf( "%d " ,vp.get(i).get( 1 ));
}
}
public static void main(String args[])
{
int [] arr = { 14 , 1101 , 10 , 35 , 0 };
int n = arr.length;
sortArr(arr, n);
}
}
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int sumOfDigit( int n)
{
int sum = 0;
while (n > 0) {
sum += n % 10;
n = n/10;
}
return sum;
}
static void sortArr( int [] arr, int n)
{
List< int []> vp= new List< int []>();
for ( int i = 0; i < n; i++) {
vp.Add( new int [2] { sumOfDigit(arr[i]), arr[i] } );
}
vp.Sort((x,y)=>x[0]-y[0]);
for ( int i = 0; i < n; i++){
Console.Write(vp[i][1]+ " " );
}
}
public static void Main()
{
int [] arr = { 14, 1101, 10, 35, 0 };
int n = arr.Length;
sortArr(arr, n);
}
}
|
Javascript
<script>
function sumOfDigit(n)
{
let sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
}
function sortArr(arr, n)
{
let vp = [];
for (let i = 0; i < n; i++) {
vp.push([sumOfDigit(arr[i]), arr[i]]);
}
vp.sort();
for (let i = 0; i < vp.length; i++)
document.write(vp[i][1], " " );
}
let arr = [ 14, 1101, 10, 35, 0 ];
let n = arr.length;
sortArr(arr, n);
</script>
|
Python3
def sumOfDigit(n) :
sum = 0 ;
while (n > 0 ) :
sum + = n % 10 ;
n = n / / 10 ;
return sum ;
def sortArr(arr, n) :
vp = [];
for i in range (n) :
vp.append([sumOfDigit(arr[i]), arr[i]]);
vp.sort()
for i in range ( len (vp)) :
print (vp[i][ 1 ], end = " " );
if __name__ = = "__main__" :
arr = [ 14 , 1101 , 10 , 35 , 0 ];
n = len (arr);
sortArr(arr, n);
|
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:
- Pass the array arr into sort function with Sum_Compare comparator function.
- 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.
- return whether sumx is less than sumy.
Below is the implementation of the above approach:
Java
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)+ " " );
}
}
}
|
C#
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]+ " " );
}
}
}
|
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
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 = " " )
|
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
Please Login to comment...