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

How to binary search in an array which is in an descending order?

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

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;

}

这可能是什么问题,我没有看到什么?

试试 foll

假设:a 是您的数组,i = startj= endx 是您要查找的元素。如果 x 不在 a

中,Foll 将 return -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;

}