二进制搜索找到的索引不正确 [英] binary search found index is incorrect

查看:72
本文介绍了二进制搜索找到的索引不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有用于二进制搜索的代码.

I have this code to binary search.

public class BinarySearch {

private static int location;
private static int a = 14;
static int[] numbers = new int[]{3, 6, 7, 11, 14, 16, 20, 45, 68, 79};

public static int B_Search(int[] sortedArray, int key) {
    int lowB = 0;
    int upB = sortedArray.length;
    int mid;
    while (lowB < upB) {
        mid = (lowB + upB) / 2;

        if (key < sortedArray[mid]) {
            upB = mid - 1;
        } else if (key > sortedArray[mid]) {
            lowB = mid + 1;
        } else {
            return mid;
        }
    }
    return -1;
}

public static void main(String[] args) {
    BinarySearch bs = new BinarySearch();
   location= bs.B_Search(numbers, a);
   if(location != -1){
       System.out.println("Find , at index of: "+ location);
   }
   else{
       System.out.println("Not found!");
   }
}
}

输出:

a = 14 找不到!

a=14 not Found!!

为什么?

推荐答案

输出:找不到a = 68!为什么?

output: a=68 not Found!! Why?

二进制搜索算法依赖于从头开始排序的输入.它假定如果发现的值大于目标值,则意味着它需要在输入中更早查找(反之亦然).

The binary search algorithm relies on the input being sorted to start with. It assumes that if it finds a value which is greater than the target one, that means it needs to look earlier in the input (and vice versa).

您的数组未排序:

static int[] numbers = new int[]{6, 3, 7, 19, 25, 8, 14, 68, 20, 48, 79};

从头开始对其进行排序,应该没问题.

Sort it to start with, and it should be fine.

这篇关于二进制搜索找到的索引不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆