WA in JNEXT of spoj--problem in logic

The link to my code is http://ideone.com/W6PZHM
I am unable to find out fault in my logic.Please help me to understand its logic

I see its a famous lexicographical problem where we need to find next number that can be formed from the given set of digits. Your code will work on some cases but not all. One of the cases being having lower digit as nth element(Eg. when n is 15483). Now there are two ways to do this.

One way is to use next_permutation built in function(in C++) that finds the next permutation using the given array which takes the fun out of it.

Second way is to solve it without any built in function. Here is a good read on the same.
Let me know if you have any doubts.

The link to my new code is http://ideone.com/GvvvrN
And I have followed the steps given in your article… But still this solution is giving me run time error.
Please help me out.And thanks