package MathMethod; //package name should begin with a lowercase character by convention
/**
* Title: 排列问题递归算法
* Description: 利用递归方法求解对象数组list[0:maxSize-1]的子数组list[k:m]的全排列
* Copyright (c) 2005
* Company: math
* @author ql213
*/
public class arrangeArithmetic { //class name should begin with an uppercase character by convention
static int size; //要排序的元素个数
static int Anum=0;
public arrangeArithmetic(int i,int j)
{
if(i>j)
{
System.out.println("Please insure that your input[i,j]:i<=j!");
return;
}
this.size=Math.abs(j-i)+1;
}
//交换对象数组的两个元素
public static void swap(Object []a,int i, int j)
{
Object temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static void perm(Object []list,int k,int m) throws Exception
{
//产生list[k:m]的所有排列
if(k==m)
{
//得到一种排列
Anum++;
System.out.print("Arrange: ");
for(int i=m-size+1;i<=m;i++)
{
System.out.print(list[i]);
}
System.out.println(" ");
}
else
{
//按照前面的递归思想产生排列
for(int i=k;i<=m;i++)
{
swap(list,k,i);
perm(list,k+1,m);//递归求解
swap(list,k,i);
}
}
}
public int ArrangeNum()
{
return Anum;//返回排列个数
}
}
{ Please use [code ] tag and check "Disable Smileys" for code listing. }
---------------------------------------------
测试结果:
Arrange: 1234
Arrange: 1243
Arrange: 1324
Arrange: 1342
Arrange: 1432
Arrange: 1423
Arrange: 2134
Arrange: 2143
Arrange: 2314
Arrange: 2341
Arrange: 2431
Arrange: 2413
Arrange: 3214
Arrange: 3241
Arrange: 3124
Arrange: 3142
Arrange: 3412
Arrange: 3421
Arrange: 4231
Arrange: 4213
Arrange: 4321
Arrange: 4312
Arrange: 4132
Arrange: 4123
The total Arrange number is: 24