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.
答案 0 :(得分:0)
鉴于您的输出只打印了两条logSize
条消息,我得出结论为logSize = 2
和anArray.length = 5000
,所以您可能意味着:
int lastNum = (logSize - 1);
为什么还要传递logSize
?
鉴于此,您声称5134 found at location 329
是不可能的。位置329将是0
。