Here is what you do
EG: 5436782
ans is 5436872
how did we arrive?
FInd least index i, such that a[i-1] >= a[i] starting from rigthmost
5436782
(8)
Now , Find least index j such that a[j-1] <= a[i-1]:
5436782
(7)
swap them
=> 5436872
Now swap all values between i and j.
Pseudocode in Python:
*def get_next(a):*
* N = len(a)*
* i = len(a)-1*
*
*
* while a[i-1] >= a[i]:*
* i -= 1*
*
*
* j = N*
*
*
* while a[j-1] <= a[i-1]:*
* j -= 1*
*
*
* a[i-1], a[j-1] = a[j-1], a[i-1]*
*
*
* i += 1*
* j = N*
*
*
* while i < j:*
* a[i-1], a[j-1] = a[j-1], a[i-1]*
* i+=1*
* j-=1*
*
*
* return a*
Source:
http://nicolas-lara.blogspot.in/2009/01/permutations.html
On Friday, December 14, 2012 11:56:16 AM UTC+5:30, tapan rathi wrote:
>
> For a given number, find the next greatest number which is just greater
> than previous one and made up of same digits.
--