递归:类似与循环,但是循环是只去不回,而递归是去了返回,在代码中也就类似与自己用自己。
能体现递归的有二分查找:
二分查找:也就是把比较的数与中间位置的数进行比较,如果等于中间位置的数就返回该索引,如果不是就把这组数组分成两个数组,再使用自己去做比较
代码演示:
public static void main(String[] args) {
int[] arr = {1, 5, 6, 7, 8, 21, 15, 17, 45};
int judge = 17;
int fast = 0;
int end = arr.length - 1;
function(arr, fast, end, judge);
}
public static void function(int[] arr, int fast, int end, int judge) {
int mid = (fast + end) / 2;
if (judge == arr[mid]) {
System.out.println("在第" + mid + "号索引");
} else if (judge > arr[mid]) {
function(arr, mid + 1, end, judge);
} else if (judge < arr[mid]) {
function(arr, fast, mid - 1, judge);
} else if (fast > end) {
System.out.println("不在数组内");
}
}
|