Let me see if I understand this problem. Let the example work with a large number of elements:
Do you need this order?
ABCDEFGHIJKLMNOPQ AQI EM CGKO BDFHJLNP
It seems simple. Create a data structure called the Interval, which has two fields: the largest lower bound and the least upper bound. That is, which elements are the biggest thing that is below the interval and the smallest thing that is above the interval. The algorithm is as follows:
Input: the size of the array. Yield the first item
Let's look at the example above. We have an array of ABCDEFGHIJKLMNOPQ .
Yield A Yield Q Enqueue AQ. The queue is now AQ Is the queue empty? No. Dequeue the queue. It is now empty. current is AQ Is the current interval empty? no. The middle is I. Yield I. Enqueue AI. The queue is now AI. Enqueue IQ. The queue is now AI, IQ. Is the queue empty? No. Dequeue the queue. It is now IQ. current is AI. Is the current interval empty? No. The middle is E. Yield E. Enqueue AE. The queue is now IQ, AE. Enqueue EI. The queue is now IQ, AE, EI Is the queue empty? No. Dequeue. The queue is now AE, EI current is IQ The middle is M Yield M. Enqueue IM Enqueue MQ. The queue is now AE, EI, IM, MQ OK, let start skipping some steps here. The state of the queue and the yields are: Yield C EI, IM, MQ, AC, CE Yield G IM, MQ, AC, CE, EG, GI Yield K MQ, AC, CE, EG, GI, IK, KM yield O AC, CE, EG, GI, IK, KM, MO, OQ yield B CE, EG, GI, IK, KM, MO, OQ, AB, BC OK, skip more steps... Yield D, F, H, J, L, N, P Queue is now AB, BC, CD, DE, ... PQ Every interval is now empty, so we skip all of htem and we are done.
Make sense?
The trick here is to notice that the order you want is a wide selection of wood. You just need to be able to "see" the array in the tree structure that you want to cross.
By the way, the ordering seems a little strange. For the most part, ordering "divides the range into two parts and gives the middle of each range in the first place." Why, then, are the two extremes inferior first, and not the last? I would find an order:
ABCDEFGHIJKLMNOPQ I EM CGKO BDFHJLNP AQ
more intuitively obvious; if things โin the middleโ always take precedence over things โto the extremes,โ then the extremes should go last, not first.