`
standalone
  • 浏览: 611348 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

How to generate permutations

阅读更多

The following algorithm generates the next permutation lexicographically after a given permutation. It changes the given permutation in-place.

  1. Find the largest index  k   such that  a [k ] <  a [k   + 1] . If no such index exists, the permutation is the last permutation.
  2. 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 .
  3. Swap  a [k ] with  a [l ].
  4. 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 + " .");
	}

}
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics