二进制搜索无法找到正确的密钥

时间:2015-11-04 15:40:46

标签: java binary

好的,所以我在java中编写了一个程序,它从文件中读取值并将它们存储在一个数组中,然后将它们传递给二进制类,二进制代码将在其中搜索密钥。现在,如果密钥在文件中列出,它将显示位置和密钥,但如果未列出密钥,则输出密钥未列出。 我的程序工作正常如果我的密钥是6474或我相信直到索引达到500但是一旦找到密钥(7988)它显示密钥未列出,即使密钥在文件中。任何帮助将不胜感激.......

P.S。我的文件中有667个值,我的密钥是7988.不,它不会引发任何错误。

这里是代码:

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;


public class MyMain {

public static void main(String[] args) throws IOException {

    int key = 8681;
    int num;
    int phySize = 5000;
    int logSize = 0;
    int[] anArray = new int[phySize];

    File myFile = new File("integers");
    Scanner sc = new Scanner(myFile);

    while (sc.hasNext()) {
        num = sc.nextInt();
        System.out.println(" logSize " + num);
        anArray[logSize] = num;
        logSize = logSize + 1;
    }

    // System.out.println(" The log size is " + logSize);

    BinSearch Bin = new BinSearch();
    SeqSearch Seq = new SeqSearch();



    int count = -1;

    while (count < logSize) {
        count++;
        if (anArray[count] == key) {
            break;
        }
    }

    int j = Bin.BinarySearch(anArray, logSize, key);
    int k = Seq.sequentialSearch(anArray, logSize, key);
    //System.out.println(" The number of count is " + count);

    // System.out.println(" The logical Size is " + logSize);

     }
   } 

二分查找类:

 public class BinSearch implements IBinarySearch {

 public int BinarySearch(int[] anArray, int logSize, int key) {

    int firstNum = 0;
    int lastNum = (anArray.length - 1);
    int middleNum = (firstNum + lastNum) / 2;

    while (firstNum <= lastNum) {
        if (anArray[middleNum] < key)
            firstNum = middleNum + 1;
        else if (anArray[middleNum] == key) {
            System.out.println(key + " found at location "
                    + (middleNum + 1) + ".");
            break;
        } else
            lastNum = middleNum - 1;

        middleNum = (firstNum + lastNum) / 2;

    }

    if (firstNum > lastNum){
        System.out.println(key + " is not present in the list.\n");
    }
    return key;
   }

  }

输出1:

 logSize 5134
 logSize 5743
 5134 found at location 329.

带有更大键的第二个输出:

logSize 9974
logSize 9990
9990 is not present in the list.

1 个答案:

答案 0 :(得分:0)

鉴于您的输出只打印了两条logSize条消息,我得出结论为logSize = 2anArray.length = 5000,所以您可能意味着:

int lastNum = (logSize - 1);

为什么还要传递logSize

鉴于此,您声称5134 found at location 329是不可能的。位置329将是0