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 + " .");
	}

}
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值