【问题标题】:where is my index out of bounds error happening?我的索引越界错误发生在哪里?
【发布时间】:2020-04-29 18:04:06
【问题描述】:

在编写我的第一个二分搜索方法时遇到问题。

public static int binarySearch(int [] a, int b){
    int mid = a[a.length-1]-a[0]/2;
    int high = a[a.length-1];
    int low = a[0];
    int found = -2;

    while (high > low){
      for (int i = high; i >= mid; i--){
        if (a[i] == b){
          found = i;
        }
      }
      for (int x = 0; x <= mid; x++){
        if (a[x] == b){
          found = x;
        }
      }
      if (a[mid] < b){
        low = mid;
        mid = high-low/2;
      } else if (a[mid] > b){
        high = mid;
        mid = high-low/2;
      } else if (a[mid] == b){
        found = mid;
      }
    }
  return found;
  }

我在跑步者的调用语句中收到一个索引越界错误。我一直在搞乱 for 循环,但我什至不确定这是怎么回事。

【问题讨论】:

  • 看起来您的 lowmidhigh 变量已初始化为从数组中读取的值。它们应该是索引。
  • 也不确定两个for 循环发生了什么。这些不属于典型的二分搜索算法。

标签: java for-loop while-loop binary-search


【解决方案1】:

考虑案例:
a = [100, 200, 300, 400, 500]
b = 200

在您的代码中,int mid = a[a.length-1]-a[0]/2; 会将mid 的值分配为500-100/2 = 450

我可以看到,在您前面的代码中的多个位置,您正在使用 a[mid],这意味着您要求在索引 450 处获取 a 的元素。但是,您的数组只有 5 个元素。

基本上,当您应该使用索引时,您正在使用数组中的值。

【讨论】:

    【解决方案2】:

    您的binarySearch 方法不正确。 lowhighmid 变量应该是数组的索引,而不是实际值。下面是它的一个简单实现。

     public static int binarySearch(int [] a, int b){
        int mid;
        int high = a.length-1;
        int low = 0;
    
        while (high > low){
            mid = (low + high) / 2;
            if (a[mid] > b) 
                high = mid - 1;
            else if (a[mid] < b) 
                low = mid + 1;
            else 
                return mid;
        }
        return -2; // not found the key
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-06
      • 2015-03-22
      • 1970-01-01
      • 2013-10-13
      • 2015-01-10
      • 2014-01-27
      • 2021-04-03
      相关资源
      最近更新 更多