-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathRecursion.java
More file actions
140 lines (102 loc) · 3.11 KB
/
Recursion.java
File metadata and controls
140 lines (102 loc) · 3.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package basic;
/**
* Created by ozc on 2018/3/16.
*
* @author ozc
* @version 1.0
*/
public class Recursion {
public static void main(String[] args) {
int[] arrays = {1, 1, 2, 3, 5, 8, 13, 21};
//bubbleSort(arrays, 0, arrays.length - 1);
//int fibonacci = fibonacci(10);
System.out.println("公众号:Java3y--------------------------------------------------" );
hanoi(3, 'A', 'B', 'C');
System.out.println("公众号:Java3y--------------------------------------------------" );
}
/**
* 汉诺塔
* @param n n个盘子
* @param start 起始柱子
* @param transfer 中转柱子
* @param target 目标柱子
*/
public static void hanoi(int n, char start, char transfer, char target) {
//只有一个盘子,直接搬到目标柱子
if (n == 1) {
System.out.println(start + "---->" + target);
} else {
//起始柱子借助目标柱子将盘子都移动到中转柱子中(除了最大的盘子)
hanoi(n - 1, start, target, transfer);
System.out.println(start + "---->" + target);
//中转柱子借助起始柱子将盘子都移动到目标柱子中
hanoi(n - 1, transfer, start, target);
}
}
/**
* 费波纳切数列
* @param n
* @return
*/
public static int fibonacci(int n) {
if (n == 1) {
return 1;
} else if (n == 2) {
return 1;
} else {
return (fibonacci(n - 1) + fibonacci(n - 2));
}
}
public static void bubbleSort(int[] arrays, int L, int R) {
int temp;
//如果只有一个元素了,那什么都不用干
if (L == R) ;
else {
for (int i = L; i < R; i++) {
if (arrays[i] > arrays[i + 1]) {
temp = arrays[i];
arrays[i] = arrays[i + 1];
arrays[i + 1] = temp;
}
}
//第一趟排序后已经将最大值放到数组最后面了
//接下来是排序"整体"的数据了
bubbleSort(arrays, L, R - 1);
}
}
/**
* 递归,找出数组最大的值
*
* @param arrays 数组
* @param L 左边界,第一个数
* @param R 右边界,数组的长度
* @return
*/
public static int findMax(int[] arrays, int L, int R) {
//如果该数组只有一个数,那么最大的就是该数组第一个值了
if (L == R) {
return arrays[L];
} else {
int a = arrays[L];
int b = findMax(arrays, L + 1, R);//找出整体的最大值
if (a > b) {
return a;
} else {
return b;
}
}
}
/**
* 递归,1+2+3+4+....+100(n)
*
* @param n 要加到的数字,比如题目的100
* @return
*/
public static int sum(int n) {
if (n == 1) {
return 1;
} else {
return sum(n - 1) + n;
}
}
}