【问题标题】:BinarySearch. Print out the elements that are compared to the target?二进制搜索。打印出与目标比较的元素?
【发布时间】:2016-04-18 04:10:24
【问题描述】:

我正在努力解决这个教科书问题。我必须对 BinarySearch 函数进行哪些修改,以便它打印出与目标进行比较的数组元素序列?

public class BinarySearch {

public static int binarySearch(int[] A, int p, int r, int target) {
   int q;
   if(p > r) {
      return -1;
   }else {
      q = (p + r)/2;
      if(target == A[q]) {
         return q;
      } else if (target < A[q]) {
          return binarySearch(A, p, q-1, target);
      } else {
          return binarySearch(A, q+1, r, target);
      }
   }
}

public static void main(String[] args) {
   int[] B = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   System.out.println(binarySearch(B, 0, B.length-1, 7));
   System.out.println(binartSearch(B, 0, B.length-1, 2));
   System.out.println(binarySearch(B, 0, B.length-1, 11));
  }
}

【问题讨论】:

  • 你在打印时拼错了binarySearchSystem.out.println(binartSearch(B, 0, B.length-1, 2));。其余代码看起来没问题

标签: java recursion binary-search


【解决方案1】:

如果您想打印与目标比较的元素,只需在您的方法binarySearch 中的比较之前添加一个打印语句:

q = (p + r)/2;
System.out.print(A[q]+" ");  //  <---- here
if(target == A[q]) {
    System.out.print("-> "); //  <---- here
    return q;
} 

如果找不到目标,您也可以添加System.out.print("-&gt; "); 以获得更好的表示

if(p > r) {
   System.out.print("-> "); // <-- here
   return -1;
}

这里箭头前面的数字是与目标比较的元素,箭头后面的数字是方法的返回值。

输出:

5 8 6 7 -> 6
5 2 -> 1
5 8 9 10 -> -1

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2017-01-26
    • 2010-12-06
    • 2021-12-15
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多