Java – algorithm for looping arrays from the middle to the outside?

I'm working on a divide and conquer algorithm (actually fitting the curve to multiple input points) For the "split" part, I need to calculate the error term of each point. If the error exceeds a given threshold, I want to split the curve at that point and process the left and right parts of the input separately A simple cycle is the trick; However, starting from the present part, it is advantageous to work outside (to clarify: if I find a point where the error is too large, I recursively call and generate a separate curve for the left and right parts - if all points are within the threshold, then my curve is suitable for me to return)

After a little headache, I came up with this point (the points are in the array, and the current part is from StartIndex to endindex)

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, starting near the middle, forward an index, two backward, three forward, four backward... Its work, I'm sure it's efficient, but it makes me think there should be a cleaner way to do it. In particular, I finally have to check the Java language specification to ensure that the statements in the update expression are evaluated in order (even if it's not a sequence operator in C / C + +)

Any idea would be appreciated Is there a cleaner way?

Solution

This will 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
}

Edit: an error was implemented in index lookup

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>