我的BinarySearch代码无效。我的代码有什么问题?

时间:2017-07-21 16:18:28

标签: java binary-search

我正在尝试用Java编写二进制搜索的代码。但光标只是堆栈而无法看到任何答案。我需要帮助来解决这个问题。我相信我写的代码是有道理的。不确定!

public class BinarySearch {
public static void main(String[] args) {

    int test[] = {1, 3, 5, 6};

    // int ans = BinarySearch(test, 6);

    System.out.println(BinarySearch(test, 1));
    //while (counter <=test.length){
    //System.out.println(test[counter]);
    //counter++;
}

public static int BinarySearch(int searcharr[], int key) {

    int left, fulllength, midpoint;

    left = 0;
    midpoint = 0;
    fulllength = searcharr.length;

    while (left <= fulllength) {

        midpoint = (left + fulllength) / 2;

        if (searcharr[midpoint] == key) {

            return searcharr[midpoint];

        } else if (searcharr[midpoint] > key) {
            left = midpoint - 1;
        } else {
            fulllength = midpoint + 1;
        }
        // left++;
    }
    return -1;
}
}

2 个答案:

答案 0 :(得分:1)

这是一个非常小的问题

// searcharr[midpoint] = 5
//  5 > 1   , execute else if , mean
//  1  3  5  6
//     ^  should be new fulllength = mid-1 

// what you are doing is 
//  1  3  5  6
//     ^  left = mid-1 which is wrong

else if (searcharr[midpoint] > key) {
            left = midpoint - 1;
        }     
else {
      fulllength = midpoint + 1;
    }

所以最后的代码是

   while (left<=fulllength){

        midpoint = (left + fulllength)/2;
        System.out.println(midpoint + " "+left+" "+fulllength);

        if(searcharr[midpoint]==key)
        {
           //return searcharr[midpoint];
           return midpoint; // return position instead of value 
        }
        else if (searcharr[midpoint]>key)
        {
           fulllength = midpoint - 1;
        }
        else 
        {
          left = midpoint + 1;
        }
   }    

答案 1 :(得分:0)

您在错误索引处启动了高位键,并且if语句中的逻辑比较不正确。您还设置在每个循环结束时错误地更改了左侧和全长。他们应该被交换。这应该有用。

public static int BinarySearch(int searcharr[], int key) {

int left, fulllength, midpoint;

left = 0;
midpoint = 0;
fulllength = searcharr.length - 1; //fulllength starts at incorrect index.

while (left <= fulllength) {

    midpoint = (left + fulllength) / 2;

    if (searcharr[midpoint] == key) {

        return searcharr[midpoint];
        // the comparison inside was incorrect
    } else if (searcharr[midpoint] < key) {
        left = midpoint + 1; //instead of midpoint - 1
    } else {
        fulllength = midpoint - 1; //instead of midpoint + 1
    }
    // left++;
}
return -1;
}