How to generate permutations recursively

I have posted code to calcuate permutations in order,  this is another more short recursive one of generating non-order permutations.

package alg_test;

public class Permutation2 {
	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("");
	}
	public void permutate(int a[], int start, int end){
		if(start == end){
			printArray(a);
		}
		else {
			for(int i=start;i<=end;i++){
				swap(a, i, start);
				permutate(a, start+1, end);
				swap(a, i, start);
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]={1,2,3,4};
		Permutation2 p  = new Permutation2();
		p.permutate(a, 0, a.length-1);
	}

}
 

你可能感兴趣的:(J#)