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)

2^{n}

### Recently Asked Questions

- Two positive electric charges, one +q and one unknown, are held fixed at corners of a right triangle with side lengths s(for +q) and 2s(for unknown). If the

- If Anybody is familiar with the extraction of Trimyirtstin experiment, what is the purpose of performing a simple distillation in this experiment instead of

- Need some help with this. A contractor's records during the least five weeks indicate the number of job requests: