Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Created May 7, 2014 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jingz8804/fda7009ea3b67728e6f9 to your computer and use it in GitHub Desktop.
Save jingz8804/fda7009ea3b67728e6f9 to your computer and use it in GitHub Desktop.
public class NextPermutation{
public void nextPermutation(int[] num) {
if(num == null || num.length == 0) return;
int len = num.length;
if(len == 1) return;
int i = len - 2;
while(i >= 0 && num[i] >= num[i+1]) i--;
if(i >= 0){
int ceilingIndex = findCeiling(num, num[i], i+1, len-1);
swap(num, i, ceilingIndex);
}
// I used to sort this part. No need at all. They are always in descending order
// if they are not, we will not be at the current switch point.
reverse(num, i+1, len-1);
}
private int findCeiling(int[] num, int target, int low, int high){
int j = high;
while(j >= low && target >= num[j]) j--; // be sure to use >=
return j;
}
private void reverse(int[] num, int left, int right){
while(left <= right) swap(num, left++, right--);
}
private void swap(int[] num, int i, int j){
int tmp = num[i];
num[i] = num[j];
num[j] = tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment