Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created June 7, 2017 15:13
Show Gist options
  • Save rupalbarman/3e5a3b003f3e4a1a2bee3b722548f65e to your computer and use it in GitHub Desktop.
Save rupalbarman/3e5a3b003f3e4a1a2bee3b722548f65e to your computer and use it in GitHub Desktop.
Next greatest permutation of a number, without using inbuilt function
/*
Following is the algorithm for finding the next greater number.
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 “53(4)976”, 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 “97(6)”. 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 536(974). We get “536479” which is the next greater number for input 534976.
*/
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string num;
cin >> num;
int n = num.length();
int i = 0, j = 0;
for(i=n-1; i>=1; i--) {
if (num[i-1] < num[i]) break;
}
if (i==0) {
cout << -1; // means not possible
} else {
i -= 1; // we need i-1, which is smaller in real
for(j=i+1; j<n; j++) {
if (num[j] < num[i]) break;
}
j -= 1; // j increments while coming out of the loop
swap(num[i], num[j]);
sort(num.begin()+i+1, num.end());
cout << num;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment