全排列算法,递归的实现
public class AllSort {
public static void main(String[] args) {
String str[] = { "1", "2", "3" };
permutation(str, 0, str.length);
}
static void swap(String[] str, int start, int end) {
String tmep = str[start];
str[start] = str[end];
str[end] = tmep;
}
static void permutation(String[] str, int start, int end) {
if (start == end - 1) {
for (int i = 0; i < end; i++) {
System.out.print(str[i]);
}
System.out.println();
} else {
for (int i = start; i < end; i++) {
swap(str, start, i);
permutation(str, start + 1, end);
swap(str, start, i);
}
}
}
}
Java排序
int[] array = new int[] { 34, 68, 1, 832, 5, 87 };
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
int j, temp;
for (int i = 1; i < array.length; i++) {
temp = array[i];
for (j = i; j > 0 && temp < array[j - 1]; j--) {
array[j] = array[j - 1];
}
array[j] = temp;
}
int postion, temp;
for (int i = 0; i < array.length; i++) {
postion = i;
for (int j = array.length - 1; j > i; j--) {
if (array[j] < array[postion]) {
postion = j;
}
}
temp = array[i];
array[i] = array[postion];
array[postion] = temp;
}