查找
package com.kaibing.sortandfind; import org.junit.jupiter.api.Test; public class Find { public int[] arr = {1, 2, 3, 4, 5}; @Test public void binaryFind() { System.out.println(binaryFindBody(0, arr.length - 1, arr, 58)); } /** * 二分查找:基本思想是把数组分成两个分别查找 * 时间:平均=O(log2n) | 最坏=O(log2n) * 空间:O(log2n) * 稳定性:稳定 */ public int binaryFindBody(int head, int tail, int[] arr, int find) { if (head > tail) { return -1; } int target = (head + tail) / 2; if (arr[target] == find) { return target; } else if (arr[target] > find && target > 0) { return binaryFindBody(head, target - 1, arr, find); } else { return binaryFindBody(target + 1, tail, arr, find); } } }