数据结构 递归解决二分查找 数据结构(八)

1. 二分查找也属于结果集缩小案例:

package com.nami.algorithm.study.day06;

/**
 * beyond u self and trust u self.
 *
 * @Author: lbc
 * @Date: 2023-09-05 10:09
 * @email: [email protected]
 * @Description: keep coding
 */
public class BinarySearch {

    private static int search(int[] target, int search, int i, int j) {
        if (i > j) {
            return -1;
        }
        int temp = (i + j) >>> 1;
        if (target[temp] < search) {
            return search(target, search, temp + 1, j);
        } else if (target[temp] > search) {
            return search(target, search, i, temp - 1);
        } else {
            return temp;
        }

    }

    public static int search0(int[] target, int search) {
        return search(target, search, 0 , target.length);
    }

    public static void main(String[] args) {
        int[] target = new int[]{1, 2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 19, 23, 24, 25, 26, 27, 28, 57, 234};
        int result = search0(target, 234);
        System.out.println(result);
    }
}

你可能感兴趣的:(数据结构与算法,数据结构,java,算法)