On re-arranging digits in number 1862
next highest number is 2168
On re-arranging digits in number 22405
next highest number is 22450
What is an algorithm for finding next highest number?
On re-arranging digits in number 1862
next highest number is 2168
On re-arranging digits in number 22405
next highest number is 22450
What is an algorithm for finding next highest number?
Here is a summary of an algorithm that does what you want. If you want more details, code, or a proof of the correctness of the algorithm, show us more of what you have done so far.
Let's use 1862
as an example. Scan the digits of that number from the right-most digit to the left until you find a consecutive pair of digits where the left digit is smaller than the right digit. In this case that is the 18
. Let's call that left digit the "pivot" position (1
here). You will now rearrange the digits in the number starting with that pivot. Replace the pivot with the next-larger digit that is anywhere to the right of it (2
in this case). Then after that digit, place all the other digits that used to be at or right of the pivot (186
in this case) in ascending order (168
here). The result is your answer 2168
.
In your other example 22405
you scan back and stop at 05
. You replace the 0
with the 5
then put the other digit(s), 0
in this case, after it in increasing order. So you leave the 224
alone and end up with 22450
.
If, in your backwards scan, you do not find any consecutive pair of digits where the left digit is smaller than the right digit, then there is no larger number with those digits.
There is a trick to speed up the placement of the digits in increasing order, but I'll leave that to you.