---
title: "How to generate permutations recursively"
author: "standalone"
date: "2011-06-18T17:02:20Z"
tags: []
categories: ["编程语言"]
slug: "how-to-generate-permutations-recursively"
draft: false
lastmod: "2011-06-18T17:02:20Z"
id: 1097464
url: "https://standalone.iteye.com/blog/1097464"
---

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);
	}

}
```