算法遍历从中间向外数组?遍历、数组、向外、算法

2023-09-11 05:35:04 作者:你的小仙女

我工作的一分而治之算法(事实上,一个没有曲线拟合到多个输入点)。为分的一部分,我需要计算的误差项的每个点,并且如果误差超过给定阈值,我要拆分的曲线在该点,并分别处理输入的左和右的部分。简单循环的伎俩;但将是有利的,我开始在当前节中段和工作向外。 (澄清:如果我发现它的误差太大了点,我递归调用,并为左,右部分单独的曲线 - 如果所有的点都内的阈值,那么我的曲线拟合和我回)

在一个有点小麻烦,我想出了这个(点都在一个阵列,而当前部分是由的startIndex endIndex的含):

  INT步骤=(endIndex的+ 1的startIndex);
INT I =(在startIndex + endIndex的)>> 1;
INT stepdir = 1;
对于(INT Q = 0; Q<步骤,Q +,I + = stepdir * Q,stepdir = -stepdir)
{
   //测试点我在这里并返回早期如果误差超过阈值
}
 

在换句话说,从靠近中间,去一个索引前进,两回,三进,四回...它的工作原理,我敢肯定,这是有效的,但它让我觉得应该有一个更清洁的方式要做到这一点,特别是,我最后不得不检查Java语言规范,以确保对更新前pression在报表并评估序列(虽然,不是一个序列算,因为它是在C / C ++)。

任何想法感激AP preciated。是否有一个更清洁的方式?

解决方案 二叉树遍历算法

这将是更具可读性恕我直言

 的(INT Q = 0; Q<步骤,Q ++){

   INT指数= I +(Q%2 == 0的q / 2: - (Q / 2 + 1)); //索引查找这里
}
 

编辑:实现了索引查找一个错误

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?

解决方案

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
}

Edit: realized a mistake in the index lookup