The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.
- Find the largest index k such that a [k ] < a [k + 1] . If no such index exists, the permutation is the last permutation.
- Find the largest index l such that a [k ] < a [l ] . Since k + 1 is such an index, l is well defined and satisfies k < l .
- Swap a [k ] with a [l ].
- Reverse the sequence from a [k + 1 ] up to and including the final element a [n ].
After step 1, one knows that all of the elements strictly after position k form a weakly decreasing sequence, so no permutation of these elements will make it advance in lexicographic order; to advance one must increase a [k ]. Step 2 finds the smallest value a [l ] to replace a [k ] by, and swapping them in step 3 leaves the sequence after position k in weakly decreasing order. Reversing this sequence in step 4 then produces its lexicographically minimal permutation, and the lexicographic successor of the initial state for the whole sequence.
package alg_test;
public class Permutation {
int count = 0;
void swap(int a[], int i, int j)
{
int temp = a[i];
a[i]=a[j];
a[j]= temp;
}
void printArray(int a[]){
for(int i=0;i<a.length;i++) System.out.print("\t"+a[i]);
System.out.println("");
}
boolean calcNextPermutation(int a[]){
int length = a.length;
if (length == 0 || length == 1) return false;
int i = length - 1;
while(a[i-1] > a[i]) {
i--;
if(i==0) return false;
}
int k = i-1;
int j = a.length - 1;
while(a[j] < a[k] ) j--;
int l = j;
swap(a, k, l);
k++;
j = a.length -1;
while(k<j){
swap(a, k, j);
k++;
j--;
}
count++;
printArray(a);
return true;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Permutation p = new Permutation();
int a[] = {1,3,5,7,9};
p.count = 1;
p.printArray(a);
while(p.calcNextPermutation(a)){
}
System.out.println("Total " + p.count + " .");
}
}
本文介绍了一个算法,该算法可以生成给定排列的下一个字典序排列,并通过Java代码实现了这一算法。文章详细解释了如何找到合适的元素进行交换以及如何反转部分序列来得到下一个更大的排列。
4331

被折叠的 条评论
为什么被折叠?



