交换相邻法:
{1,2,......,n}
想得到该集合的全排列,可通过获取{1,2,.....,n-1}的全排列,然后将n插入到n-1集合的全排列中,即可获取n的全排列。
实现代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AllSortArray {
static int totalLength = 0;
public static void main(String[] args) {
int []array = {1,2,3,4,5};
List<Integer> temp = new ArrayList<Integer>();
sortArray(array,temp,0);
System.out.println("总共记录:" + totalLength);
}
public static void sortArray(int[] array,List<Integer> temp,int index){
//取到要排序的值
if(index >= array.length){
System.out.println(Arrays.toString(temp.toArray()));
totalLength++;
return;
}
int value = array[index];
//首次插入进行排序
for(int i = 0; i < temp.size() + 1;i++){
List<Integer> temp_array = new ArrayList<Integer>();
temp_array.addAll(temp);
temp_array.add(i, value);
sortArray(array, temp_array, index + 1);
}
}
}