【发布时间】:2014-12-03 04:18:33
【问题描述】:
这是一种使用二进制搜索在 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
【问题讨论】:
-
我建议你不要这样做。建立索引。几十年前,我做过文件二进制搜索的实验。结论是,这就是我们拥有 B 树的原因。
-
这是一个学校项目,这些是要求。无论如何,我已经用它玩了一些,即使我不完全理解它,它也能正常工作。
标签: java search binary randomaccessfile