Skip to content

Instantly share code, notes, and snippets.

@BillRizer
Created January 31, 2024 23:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BillRizer/def08826e6824ccc7458432965ae87ba to your computer and use it in GitHub Desktop.
Save BillRizer/def08826e6824ccc7458432965ae87ba to your computer and use it in GitHub Desktop.
Binary search in Txt file with line format: ID | any | any
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.")
@BillRizer
Copy link
Author

file_name.txt
1 | anything in first line | other | ...
3 | anything in second line | other | ...
4 | anything in third line | other | ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment