首页 > 代码库 > 全排列递归算法

全排列递归算法

import java.util.Scanner;

public class FullArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner=new Scanner(System.in);
		int n=scanner.nextInt();
		int a[]=new int [n];
		for (int i = 0; i < a.length; i++) {
			a[i]=i+1;
		}
		fullArray(a, n, 0);
	}
	
	public static void fullArray(int a[],int n, int index) {
		if (index>=n) {
			for (int i = 0; i < a.length; i++) {
				System.out.print(a[i]+" ");
			}
			System.out.println();
			return;
		}
		for (int i = index; i < a.length; i++) {
			swap( a, i, index);
			fullArray(a, n, index+1);
			swap(a, i,index);
		}
	}
	
	public static void  swap(int a[], int i, int j) {
		int t=a[i];
		a[i]=a[j];
		a[j]=t;
	}
}