Question: How to use Binary Search to search in a text file(C language) For example, a text file that contains a list of North American phone
How to use Binary Search to search in a text file(C language)
For example, a text file that contains a list of North American phone number prefixes:
201200Jersey City NJ
201202Hackensack NJ
201203Hackensack NJ
201204Jersey City NJ
201205Jersey City NJ
201206Hackensack NJ
201207Newark NJ
201208Jersey City NJ
201209Jersey City NJ
201210Union City NJ
201212Hackensack NJ
....etc.
On each line, the string is right next to the six digit prefix. It is suffixed with spaces so it is always exactly 25 digits long. Each line is separated from the next line by one next-line character . Hence each line consists of exactly 6 + 25 + 1 = 32 characters. Also, the text file is sorted by ascending prefixes.
I need to write a program that always take two arguments: the text filename and a prefix. The program must open the file and search it for the location identified by the prefix specified by the second argument. And the prefix must consist of six digits, which are all numerical (0 thru 9).
And I'm supposed to base my program only on the system calls open, read, write, lseek and close. (Can not use fopen, fread, fprintf, etc.)
For a fast searching method, I'm thinking to use Binary search to do it, but also get stuck on writing the code...
I'm a begnninr in C language, thanks for any helps I can get!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
