not passing any test case
code link-https://ide.codingblocks.com/s/203191
What is wrong in my logic
Your logic is wrong, you are just comparing the adjacent digits, for example 1 4 4 4 2 so according to your logic it will be 4 1 4 4 2 but it should be 2 4 4 4 1
The algorithm you can follow here can be:-
- If all digits sorted in descending order, then output is always “Not Possible”. For example, 4321.
- If all digits are sorted in ascending order, then we need to swap last two digits. For example, 1234.
- For other cases
I) Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is “534976”, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is “Not Possible”.
II) Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For “534976″, the right side of 4 contains “976”. The smallest digit greater than 4 is 6.
III) Swap the above found two digits, we get 536974 in above example.
IV) Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get “536479” which is the next greater number for input 534976.
BUT doing this will be tedious task, so another EASY way to do this is to use C++ STL function next_permutation().
code for it is just 1 line :- next_permutation(Arr,Arr+n)
now just print the array.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.