Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to loop over an array from the middle outwards?

I'm working on a divide-and-conquer algorithm (in fact, one that does curve fitting to a number of input points). For the 'divide' part, I need to calculate an error term for each point, and if the error exceeds a given threshold, I wish to split the curve at that point and process the left and right sections of the input separately. A simple loop does the trick; but it would be advantageous for me to start at the middle of the current section and work outwards. (To clarify: if I do find a point whose error is too large, I recursively call and generate separate curves for the left and right sections - if all the points are within the threshold, then my curve fits and I return).

After a bit of head-scratching, I came up with this (the points are in an array, and the current section is from startIndex to endIndex inclusive):

int steps = (endIndex+1-startIndex);
int i = (startIndex+endIndex)>>1;
int stepdir = 1;
for(int q=0; q<steps; q++, i+=stepdir*q, stepdir=-stepdir)
{
   // test point i here and return early if error exceeds threshold
}

In other words, beginning near the middle, go one index forward, two back, three forward, four back... It works, and I'm sure it's efficient, but it strikes me that there should be a cleaner way to do it, in particular, I ended up having to check the Java language spec to make sure that the statements in the for update expression did evaluate in sequence (even though , is not a sequence operator as it is in C/C++).

Any ideas gratefully appreciated. Is there a cleaner way?

like image 842
Chris Nash Avatar asked Jul 26 '11 23:07

Chris Nash


1 Answers

This would be more readable imho

for (int q=0; q < steps; q++) {
   int index = i + ( q% 2 == 0 ? q/2 : -(q/2+1)); //index lookup here
}
like image 119
jontro Avatar answered Oct 21 '22 12:10

jontro