java - 如何在降序排列的数组中进行二分查找?

标签 java binary-search

我的代码不起作用,我希望能够在降序排列的数组中进行二分搜索。

static int searchDescendingGT( double[] a, int i, int j, double x )
{
  while(i!=j){
    // | >x | unknown | >=x |
        int m = i+(j-i)/2;

        if (a[m]<x){
        j = m; 
        }
        else{
         i = m+1; 
        }
    }
    return i;

}

它可能存在什么问题以及我没有看到什么?

最佳答案

尝试follow

假设:a是你的数组,i = startj= endx是元素你正在努力寻找。如果 x 不在 a

中,Foll 将返回 -1
static int searchDescendingGT(double[] a, int i, int j, double x) {
    while (i <= j) {

        int m = (i + j) / 2;

        if (a[m] == x) {
            return m;
        } else if (a[m] < x) {
            j = m - 1;
        } else {
            i = m + 1;
        }
    }
    return -1;

}

关于java - 如何在降序排列的数组中进行二分查找?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36826661/

相关文章:

java - 如何在 SQL Wrapper 类中返回 ResultSet

java - 使用 static final unmodifiable Set as constant 来检查变量值

java - PHP Java 桥异常 - 协议(protocol)错误

java - 在二进制搜索中,如果找不到该元素,为什么约定从它应该做的地方减去一个?

java - Apache POI : is there a way to get the plus at the top instead of the bottom? 的单元格分组

c++ - lower_bound 执行二进制搜索

具有多个 vector 条件的 C++ 二进制搜索

无法弄清楚二进制搜索算法哪里出错了

c++ - 算法::binary_search call中的预期主要表达式

java - 查瓦 : JTextArea : Test a char (KeyEvent) before print it?