这是一种使用二进制搜索在RandomAccessFile中搜索目标号码的方法。它专门处理整数。我有各种各样的设置,但我得到了错误的数字。由于raf包含字节,并且一个整数包含四个字节,我认为我只是将高递减4并将低递增4,其中在常规二进制搜索中相同的操作由1完成。显然情况并非如此,而且我很难总体上围绕二进制I / O。帮助
//determines if a target number is in a RandomAccessFile using a binary search
//tracks the number of times it took to find that the number was/wasn't in the file
public static void binarySearch(){
Scanner input = new Scanner(System.in);
int target = 0; //the number being searched for
boolean targetFound = false; //indicates if the target is found
int searchCount = 0; //the number of times it took to find that the number was/wasn't in the file
System.out.print("Please enter the number you wish to search for: ");
target = input.nextInt();
try{
RandomAccessFile raf = new RandomAccessFile("Project10.dat", "r");
long low = 0;
long high = raf.length() - 1;
int cur = 0;
while(high >= low){
long mid = (low + high) / 2;
raf.seek(mid);
cur = raf.readInt();
System.out.println(cur); //for debugging
searchCount++;
if(target < cur){
high = mid - 4;
}
else if(target == cur){
targetFound = true;
break;
}
else{
low = mid + 4;
}
}
raf.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
if(targetFound == true){
System.out.println("The number " + target + " is in the file. It took " + searchCount + " tries to discover this.");
}
else{
System.out.println("The number " + target + " is not in the file. It took " + searchCount + " tries to discover this.");
}
}//end method binarySearch
答案 0 :(得分:2)
int是4个字节 所以说你的文件包含数字1 ... 20 raf.length是80(不是20),即4 * 20 你有正确的路线,但需要工作4 在这种情况下你的高价值是79而不是76(使用上面的例子) 这么高应该是长度 - 4
你可以尝试:low = 0;
long high = (raf.length() / 4) - 1 // this is in terms of elements
long mid = (low + high) / 2 ... again element rather than where in byte array
raf.seek(mid * 4) // You can use the *4 to access the correct location in bytes
cur = raf.readInt()
if(target < cur){
high = mid - 1;
}
else if(target == cur){
targetFound = true;
break;
}
else{
low = mid + 1;
}