- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Sort the numbers according to their sum of digits in C++

In this section we will see how to sort numbers according to their sum of digits. So if a number has lesser sum of digits, then that will be placed at first, then next number will be placed with larger sum of digits.

data = {14, 129, 501, 23, 0, 145}

after sorting, they will be −

data = {0, 14, 23, 501, 145, 129}

Here we will create our own comparison logic to sort them. That comparison logic will be used in the sort function in C++ STL.

## Algorithm

compare(num1, num2): Begin if sum of digits of num1 < sum of digits of num2, then return 1 return 0 End

## Example

#include<iostream> #include<algorithm> using namespace std; int sumOfDigits(int n){ int sum = 0; while(n){ sum += n%10; n /= 10; } return sum; } int compare(int num1, int num2){ if(sumOfDigits(num1) < sumOfDigits(num2)) return 1; return 0; } main(){ int data[] = {14, 129, 501, 23, 0, 145}; int n = sizeof(data)/sizeof(data[0]); sort(data, data + n, compare); for(int i = 0; i<n; i++){ cout << data[i] << " "; } }

## Output

0 14 23 501 145 129

- Related Articles
- Python – Sort List items on the basis of their Digits
- Count of n digit numbers whose sum of digits equals to given sum in C++
- Python – Sort List items on basis of their Digits
- Print all n-digit numbers whose sum of digits equals to given sum in C++
- Print numbers with digits 0 and 1 only such that their sum is N in C Program.
- Sort an array according to count of set bits in C++
- Sort an array of strings according to string lengths in C++
- The sum of two numbers is 8. If their sum is four times their difference, find the numbers.
- Minimum sum of two numbers formed from digits of an array in C++
- Compute sum of digits in all numbers from 1 to n
- What are different types of computers according to their size in C?
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Sort the array of strings according to alphabetical order defined by another string in C++
- Sort an array according to the order defined by another array in C++
- Sort array according to the date property of the objects JavaScript

Advertisements