• 算法


    直接上代码:递归和while版本

     1 public class BinarySearch<T extends Comparable> {
     2 
     3     /**
     4      * 递归二分查找
     5      *
     6      * @param arr    数组
     7      * @param left   左标
     8      * @param right  右标
     9      * @param target 查找值
    10      * @return 找到返回下标,未找到返回-1
    11      */
    12     public int binarySearch(T[] arr, int left, int right, T target) {
    13         if (right < left) {
    14             return -1;
    15         }
    16         int middle = (right - left) / 2 + left;
    17         if (target.compareTo(arr[middle]) == 0) {
    18             return middle;
    19         } else if (target.compareTo(arr[middle]) < 0) {
    20             return binarySearch(arr, left, middle - 1, target);
    21         } else {
    22             return binarySearch(arr, middle + 1, right, target);
    23         }
    24     }
    25 
    26     public int binarySearch(T[] arr, T target) {
    27         return binarySearch(arr, 0, arr.length - 1, target);
    28     }
    29 
    30     /**
    31      * while方式二分查找
    32      *
    33      * @param arr    数组
    34      * @param target 查找值
    35      * @return 找到返回下标,未找到返回-1
    36      */
    37     public int whileBinarySearch(T[] arr, T target) {
    38         int left = 0;
    39         int right = arr.length - 1;
    40         while (left <= right) {
    41             int middle = (right - left) / 2 + left;
    42             if (target.compareTo(arr[middle]) == 0) {
    43                 return middle;
    44             }
    45             if (target.compareTo(arr[middle]) < 0) {
    46                 right = middle - 1;
    47             }
    48             if (target.compareTo(arr[middle]) > 0) {
    49                 left = middle + 1;
    50             }
    51         }
    52         return -1;
    53     }
    54 
    55     public static void main(String[] args) {
    56         Integer[] arr = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
    57         BinarySearch bs = new BinarySearch();
    58         System.out.println(bs.binarySearch(arr, 6));
    59         System.out.println(bs.binarySearch(arr, 0));
    60         System.out.println(bs.whileBinarySearch(arr, 11));
    61         System.out.println(bs.whileBinarySearch(arr, 3));
    62         String[] stingArr = new String[]{"A","B","B","D","E","F","G",};
    63         System.out.println(bs.whileBinarySearch(stingArr, "B"));
    64         System.out.println(bs.whileBinarySearch(stingArr, "C"));
    65         System.out.println(bs.binarySearch(stingArr, "G"));
    66     }
    67 
    68 }
  • 相关阅读:
    量子和量子化?
    ARM内核和架构都是什么意思,内核和架构的关系是什么?(转)
    线程,进程,协程
    关于Redis的问题
    python一些语法糖用法
    Python装饰器详解
    Python基础知识
    Pyinstaller安装以及参数使用
    正则表达式(特殊字符)/Xpath语法/CSS选择器
    还在为身份验证引入的Microsoft.AspNet.Identity.EntityFramework导致多上下文,生成的DB改名困扰吗?
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/12810186.html
Copyright © 2020-2023  润新知