在Java中,已排序文件中进行二进制搜索可以通过以下步骤实现:
RandomAccessFile
对象,用于读取和操作文件。RandomAccessFile file = new RandomAccessFile("sorted_file.txt", "r");
binarySearch
,接收一个RandomAccessFile
对象和要查找的关键字作为参数。public static long binarySearch(RandomAccessFile file, String key) throws IOException {
long low = 0;
long high = file.length() - 1;
while (low <= high) {
long mid = (low + high) / 2;
file.seek(mid);
file.readLine();
int cmp = key.compareTo(file.readLine());
if (cmp > 0) {
low = mid + 1;
} else if (cmp < 0) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
binarySearch
方法中,使用二进制搜索算法查找关键字。binarySearch
方法,传入已排序文件和要查找的关键字。long result = binarySearch(file, "key_to_search");
if (result != -1) {
System.out.println("Key found at position: " + result);
} else {
System.out.println("Key not found");
}
这样,您就可以在Java中的已排序文件中进行二进制搜索了。
领取专属 10元无门槛券
手把手带您无忧上云