Algorithm for what should be a simple problem

  • Thread starter Thread starter SpiffyEh
  • Start date Start date
  • Tags Tags
    Algorithm
AI Thread Summary
The discussion focuses on developing an O(log n) algorithm to find an index i such that ai = i in a sorted sequence of distinct integers. A divide-and-conquer approach is proposed, where the middle element is compared to its index to determine which half of the list to search next. If the middle element is less than its index, the search continues in the upper half; if greater, it continues in the lower half. This recursive method effectively narrows down the search space until the solution is found or the list is exhausted. The example provided illustrates the algorithm's application, confirming its efficiency and correctness.
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.
 

Similar threads

Back
Top