Это метод, который ищет целевое число в RandomAccessFile, используя двоичный поиск. Он имеет дело исключительно с целыми числами. У меня все настроено, но я получаю неправильные цифры. Поскольку raf содержит байты, а целое число содержит четыре байта, я подумал, что просто уменьшу старший на 4 и увеличим младший на 4, тогда как те же операции выполнялись на 1 в обычном двоичном поиске. По-видимому, это не так, и мне трудно понять двоичный ввод-вывод в целом. Помощь?
//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