Algorithm for what should be a simple problem

  • Thread starter Thread starter SpiffyEh
  • Start date Start date
  • Tags Tags
    Algorithm
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 6K views
SpiffyEh
Messages
191
Reaction score
0

Homework Statement



Suppose that you are given a sorted sequence of distinct integers {a1, a2, . . . , an}.
Give an O(lg n) algorithm to determine whether there exists an i index such as
ai = i. For example, in {−10,−3, 3, 5, 7}, a3 = 3. In {2, 3, 4, 5, 6, 7}, there is no
such i.

Homework Equations





The Attempt at a Solution


could this be done using a tree? For example splitting the problem in half with every iteration and checking to see if it is in the end? Or am I approaching this wrong?
 
Physics news on Phys.org
O(ln) usually implies a divide-conquer approach
Try the half eah sequence and see what O() that has
 
i know halving it repeatedly gives O(log n) but I don't see how that gets me anywhere
 
Here's a kind of rough outline. You have a sorted list of n numbers. Look at the middle of the list, and see whether an/2 == n/2. If so, you're done.

If an/2 < n/2, look in the lower half of the list.
If an/2 > n/2, look in the upper half of the list.

Do the above recursively, stopping when the size of the list is 1.

For example, suppose the list is {−10,−3, 3, 5, 7, 8 11, 12}. (I added a few numbers to your first example.)

Here n = 8

a4 = 5, so we should look in the lower half of the list; i.e., a1 through a4.

Now n = 4
a2 = -3, so we should look in the upper half of this list; namely, at a3 and a4

Now n = 2, and we see that a3 == 3 and we're done.