View the step-by-step solution to:

You have a large text file of people. Each person is represented by one line in the text file. The line starts with their ID number and after that,...

You have a large text file of people. Each person is represented by one line in the text file. The line starts with their ID number and after that, has the person's name. The lines are sorted by ID number in ascending order. 

There are n lines in this file. You write a search function that returns the name of a person whose ID number is given. 


The simplest way to do that would be to program a loop that goes through each line and compares the ID number in the line against the given ID number. If there is a match, then it returns the name in that line. This is very inefficient, because the worst-case scenario is that this program needs to go through almost everyone- the person we are looking for could be last. 


Using the fact that the file is sorted will greatly speed up the process, by allowing us to use a binary search algorithm:


We go to the middle line of the file first and compare the ID found there (P) to the given ID (Q). (If the number of lines is even, we go above or below the arithmetic middle.)


If P=Q then our algorithm terminates - we have found the person we are looking for.


If P is less than Q, that means that the person we are looking for is in the second half of the file. We now repeat our algorithm on the second half of the file. 


If P is greater than Q, that means that the person we are looking for is in the first half of the file. We now repeat our algorithm on the first half of the file. 


Of what order is the worst-case number of comparison operations that are needed for this algorithm to terminate?


n

√n

log(n)

2n

Recently Asked Questions

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question