Digit Sum Sorting

Sorting Algorithm Digit Sum Custom Comparator

Problem: Digit Sum Sorting

Write a function that takes an array of integers and returns a new array where the numbers are sorted based on the following rules:

  1. Primary sort key: Sum of the digits of the number (in ascending order).
  2. Secondary sort key: The numerical value itself (in ascending order) if two numbers have the same digit sum.

Example

For the input: [56, 65, 74, 100, 99, 68, 86, 180, 90]

  • Digit sums:
    • 56 -> 5 + 6 = 11
    • 65 -> 5 + 6 = 11
    • 74 -> 7 + 4 = 11
    • 100 -> 1 + 0 + 0 = 1
    • 99 -> 9 + 9 = 18
    • 68 -> 6 + 8 = 14
    • 86 -> 8 + 6 = 14
    • 180 -> 1 + 8 + 0 = 9
    • 90 -> 9 + 0 = 9

Sorting based on the rules gives the output:

[100, 90, 180, 56, 65, 74, 68, 86, 99]

Notes

  • Assume the input array contains at least one integer.
  • Consider edge cases such as single-digit numbers and numbers with the same digit sum.

This problem is inspired by sorting methodologies and is a good exercise for developing custom sort comparators.

Happy coding!