---
title: "How to generate permutations"
author: "standalone"
date: "2010-09-07T23:10:08Z"
tags: []
categories: ["编程语言"]
slug: "how-to-generate-permutations"
draft: false
lastmod: "2012-10-26T11:37:35Z"
id: 757948
url: "https://standalone.iteye.com/blog/757948"
---

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* ] &lt;  *a* \[*k*   + 1] . If no such index exists, the permutation is the last permutation.
2. Find the largest index  *l*   such that  *a* \[*k* ] &lt;  *a* \[*l* ] . Since  *k*   + 1   is such an index,  *l*   is well defined and satisfies  *k*   &lt;  *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 + " .");
	}

}
```