• 编码技巧之边界【笔记】


    编码技巧之边界【笔记】

    边界控制

    以二分查找为例,假设我们在一个有序数组中查找元素k,需要返回k所在的下标

    例如在【1,2,3,4,5,6】中找4,那么返回的话就要返回3

    二分查找的思路

    规定要查找的值k可能在的数组arr内下标区间a,b

    计算区间a,b的中间点m

    如果k<arr[m],将区间缩小为a,m,然后继续二分查找

    如果k>arr[m],将区间缩小为m,b,然后继续二分查找

    具体代码如下:

    package interview.loop;
    
    public class BinarySearch {
    
      /**
       * Searches element k in a sorted array.
       * @param arr a sorted array
       * @param k the element to search
       * @return index in arr where k is. -1 if not found.
       */
      public int binarySearch(int[] arr, int k) {
        int a = 0;
        int b = arr.length;
        // Loop invariant: [a, b) is a valid range. (a <= b)
        // k may only be within range [a, b).
        while (a < b) {
          int m = a + (b - a) / 2; // m = (a + b) / 2 may overflow!
          if (k < arr[m]) {
            b = m;
          } else if (k > arr[m]) {
            a = m + 1;
          } else {
            return m;
          }
        }
        return -1;
      }
    
      public static void main(String[] args) {
        BinarySearch bs = new BinarySearch();
    
        System.out.println("Testing normal data");
        System.out.println(
            bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 15));
        System.out.println(
            bs.binarySearch(new int[]{1, 2, 10, 15, 100}, -2));
        System.out.println(
            bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 101));
        System.out.println(
            bs.binarySearch(new int[]{1, 2, 10, 15, 100}, 13));
        System.out.println("======");
    
        System.out.println("Testing empty or singleton data.");
        System.out.println(
            bs.binarySearch(new int[]{}, 13));
        System.out.println(
            bs.binarySearch(new int[]{12}, 13));
        System.out.println(
            bs.binarySearch(new int[]{13}, 13));
        System.out.println("======");
    
        System.out.println("Testing data of size 2.");
        System.out.println(
            bs.binarySearch(new int[]{12, 13}, 13));
        System.out.println(
            bs.binarySearch(new int[]{12, 13}, 12));
        System.out.println(
            bs.binarySearch(new int[]{12, 13}, 11));
      }
    }
    

    感谢观看,文笔有限,博客不出彩,还请多多见谅
  • 相关阅读:
    atitit。wondows 右键菜单的管理与位置存储
    Atitit mac os 版本 新特性 attilax大总结
    Atitit。木马病毒原理机密与概论以及防御
    Atitit。木马病毒原理机密与概论以及防御
    Atitit Atitit.软件兼容性原理----------API兼容 Qa7
    Atitit Atitit.软件兼容性原理----------API兼容 Qa7
    Atitit j2ee5 jee5 j2ee6 j2ee7 jee6 jee7 新特性
    Atitit j2ee5 jee5 j2ee6 j2ee7 jee6 jee7 新特性
    mysql只显示表名和备注
    phpmyadmin 在服务起上检测到错误,请查看窗口底部
  • 原文地址:https://www.cnblogs.com/jokingremarks/p/14468528.html
Copyright © 2020-2023  润新知