1. 斐波那契数列
斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368。
下面在java中使用递归将其展示:
public static int t1 (int a){
if(a==0 || a==1){
return a;
}else {
return t1(a-1)+t1(a-2);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(t1(i));
}
}
2. 递归处理二分法
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
System.out.println(t2(arr, 0, arr.length - 1, 6));
}
public static int t2(int arr[], int start, int end, int key) {
int mid = start + (end - start) / 2;
System.out.println("start:"+start+" mid:"+mid+" end:"+end);
if (arr[mid] == key) {
System.out.println("success:" + key + "在下标" + mid + "处");
return mid;
}
if (start >= end) {
return -1;
} else if (key > arr[mid]) {
System.out.println("查找的数据大于中间值,start改变: " + ++mid);
return t2(arr, mid, end, key);
} else if (key < arr[mid]) {
System.out.println("查找的数据小于中间值,end改变: " + --mid);
return t2(arr, start, mid, key);
}
return -1;
}
3. 递归查询
public static void main(String[] args) {
int[] arr = {1, 41, 2, 3, 6, 33, 15, 21, 41, 77, 94, 12, 46};
arr = merSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
public static int[] merSort(int[] arr, int start, int last) {
if (last > start) {
//也可以是(start+last)/2,这样写是为了防止数组长度很大造成两者相加超过int范围,导致溢出
int mid = start + (last - start) / 2;
merSort(arr, start, mid);//左边数组的排序
merSort(arr, mid+1, last);//右边数组的排序
merge(arr, start, mid, last);
}
return arr;
}
// 升序
public static void merge(int[] arr, int start, int mid, int last) {
int[] temp = new int[last - start + 1];//临时定义的数组
int i = start;//定义左边数组的下标
int j = mid + 1;//定义右边数组的下标
int k = 0;
while (i <= mid && j <= last) {
if (arr[i] < arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
}
}
// 把左边的数移动到新的数组
while (i <= mid) {
temp[k++] = arr[i++];
}
// 把右边的数移动到新的数组中
while (j <= last) {
temp[k++] = arr[j++];
}
// 把新数组中的数覆盖到arr中
for (int a = 0; a < temp.length; a++) {
arr[a + start] = temp[a];
}
}
// 降序
public static void merge2(int[] arr, int start, int mid, int last) {
int[] temp = new int[last - start + 1];//临时定义的数组
int i = start;//定义左边数组的下标
int j = mid + 1;//定义右边数组的下标
int k = 0;
while (i <= mid && j <= last) {
if (arr[i] < arr[j]) {
temp[k++] = arr[j++];
} else {
temp[k++] = arr[i++];
}
}
// 把左边的数移动到新的数组
while (i <= mid) {
temp[k++] = arr[i++];
}
// 把右边的数移动到新的数组中
while (j <= last) {
temp[k++] = arr[j++];
}
// 把新数组中的数覆盖到arr中
for (int a = 0; a < temp.length; a++) {
arr[a + start] = temp[a];
}
}
总结:学习这些算法,可能实际很少运用,但是可以帮助提高我们的理解能力,开拓我们的思维。这篇博客参考了https://blog.csdn.net/qq_40688338/article/details/84837816这篇博客,在此基础上改正了原博客的代码错误。