汉诺塔问题
public class Main {
public static void main(String[] args){
Hanoi(3, 'A', 'B', 'C');
}
public static void Hanoi(int n, char from, char middle, char to){
if(n == 1){
System.out.println(from+"--->"+to);
}else{
Hanoi(n-1, from, to, middle);
System.out.println(from+"--->"+to);
Hanoi(n-1, middle, to, from);
}
}
}
归并(两个有序数组归并为一个有序数组)
public class Main {
public static void main(String[] args){
int[] a = {2, 3, 9};
int[] b = {1, 4, 6};
int[] c = new int[10];
mergeSort(a, b, c);
print(c, a.length+b.length);
}
public static void mergeSort(int[] a, int[] b, int[] c){
int aCnt = 0;
int bCnt = 0;
int cCnt = 0;
while(aCnt < a.length && bCnt < b.length){
if(a[aCnt] < b[bCnt]){
c[cCnt++] = a[aCnt++];
}else{
c[cCnt++] = b[bCnt++];
}
}
while(aCnt < a.length){
c[cCnt++] = a[aCnt++];
}
while(bCnt < b.length){
c[cCnt++] = b[bCnt++];
}
}
public static void print(int[] c, int length){
for(int i = 0; i < length; i++){
System.out.print(c[i]+" ");
}
System.out.println();
}
}
归并排序(递归与分治)
public class Main {
public static int[] a = {2, 3, 9, 1, 6, 4};
public static void main(String[] args){
int[] tmp = new int[a.length];
recursionMergeSort(tmp, 0, tmp.length-1);
print(a);
}
public static void recursionMergeSort(int[] tmp, int low, int high){
if(low == high){
return;
}else{
int mid = (low+high)/2;
recursionMergeSort(tmp, low, mid);
recursionMergeSort(tmp, mid+1, high);
merge(tmp, low, mid, high);
}
}
public static void merge(int[] tmp, int low, int mid, int high){
int i = 0;
int leftStart = low;
int rightStart = mid + 1;
int n = high - low + 1;
while(leftStart <= mid && rightStart <= high){
if(a[leftStart] < a[rightStart]){
tmp[i++] = a[leftStart++];
}else{
tmp[i++] = a[rightStart++];
}
}
while(leftStart <= mid){
tmp[i++] = a[leftStart++];
}
while(rightStart <= high){
tmp[i++] = a[rightStart++];
}
for(int j = 0; j < n; j++){
a[j + low] = tmp[j];
}
}
public static void print(int[] a){
for(int i = 0; i < a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
}