Created
January 31, 2024 23:24
-
-
Save BillRizer/def08826e6824ccc7458432965ae87ba to your computer and use it in GitHub Desktop.
Binary search in Txt file with line format: ID | any | any
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
def binary_search_in_file(file_name, desired_element): | |
start = 0 | |
end = None | |
with open(file_name, 'r') as file: | |
file_size = file.seek(0, 2) | |
end = file_size | |
while start <= end: | |
middle = (start + end) // 2 | |
file.seek(middle) | |
file.readline() | |
line_raw = file.readline().strip() | |
line = line_raw.split('|')[0] | |
if not line: | |
break # End of file | |
value = int(line) # Assuming IDs are integers | |
if value == desired_element: | |
return line_raw | |
elif value < desired_element: | |
start = middle + len(line) + 1 | |
else: | |
end = middle - 1 | |
return False | |
if len(sys.argv) != 3: | |
print("Usage:\n python3 search_binary.py file_name.txt unique_number\n") | |
else: | |
file_name = sys.argv[1] | |
desired_element = int(sys.argv[2]) | |
founded = binary_search_in_file(file_name, desired_element) | |
if founded: | |
print(founded) | |
else: | |
print(f"The element {desired_element} was not found in the file.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
file_name.txt
1 | anything in first line | other | ...
3 | anything in second line | other | ...
4 | anything in third line | other | ...