Skip to content
Advertisement

Sort a number by its digits

I have to sort a vector of integers (all integers have the same length). Integers with the same first digit must be sorted in relation to the second digits, and numbers with the same: first and second digits are sorted by third digit etc. Also, the subsequent digits are sorted alternately (once ascending and once descending)

So when I have lis = [137, 944, 972, 978, 986], I should get sorted_lis = [137, 986, 972, 978, 944]

I know how to sort by selecting digit (a)

JavaScript

I’ve tried using insertion sort, (since I have to use a stable sorting algorithm)

JavaScript

Advertisement

Answer

Solution 1: multisort with ints

A fun multisort taking advantage of list.sort being stable (as explained in that sorting howto section):

JavaScript

This first sorts by last digit, then by second-to-last, etc, until sorting by first digit. And reverse between the sorts.

Solution 2: “negate” every second digit

Another method, turning for example 1234 into 1735 (every second digit gets “negated”, i.e., subtracted from 9):

JavaScript

Solution 3: multisort with characters

Similar to your attempt, but converting to strings only once (at the expense of once converting back to ints at the end):

JavaScript

Your solution, completed

Like you said you already know how to sort by a certain digit. You just need to do that for each:

JavaScript

Benchmark

Benchmark with 100,000 random six-digit numbers:

JavaScript

Benchmark code (Try it online!):

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement