[英]For loop not continuing as expected in Java?
I'm trying to write a code to reverse increasing subarrays in Java within the same array (no new array created).我正在尝试编写代码来反转同一数组中 Java 中递增的子数组(未创建新数组)。 For example, the input of an array
items {2, 3, 4, 2, 1, 2, 3, 7, 8}
should output {4, 3, 2, 2, 8, 7, 3, 2, 1}
.例如,数组
items {2, 3, 4, 2, 1, 2, 3, 7, 8}
的输入应为 output {4, 3, 2, 2, 8, 7, 3, 2, 1}
。 My code so far is reversing the first increasing subarray, but the elements past that seem to not be looping.到目前为止,我的代码正在反转第一个递增的子数组,但过去的元素似乎没有循环。
Here's my code so far:到目前为止,这是我的代码:
public static void reverse(int[] items)
{
int start = 0;
int count = 0;
for (int i = 1; i < items.length; i++)
{
if (items[i] > items[i-1])
{
if (count < 1)
{
start = i-1;
count ++;
}
else
{
count ++;
}
}
else
{
int j, k;
for (j = start; j < count/2; j++)
{
k = items[j];
items[j] = items[count - j];
items[count - j] = k;
j++;
}
count = 0;
}
}
output:
```{4, 3, 2, 2, 1, 2, 3, 7, 8}```
You are looking back comparing items[i]
with items[i-1]
.您正在回顾比较
items[i]
和items[i-1]
。 But then how to find the end of the last increasing sequence when it ends at the last index?但是,当它在最后一个索引处结束时,如何找到最后一个递增序列的结尾呢? That caused the error.
那导致了错误。
Probably solved with if (i.= items.length - 1 && items[i] > items[i-1])
.可能用
if (i.= items.length - 1 && items[i] > items[i-1])
解决了。
Also the then-part if (items[i] > items[i-1])
could be eliminated, just responding when the sequence ends (items[i] <= items[i-1]`.另外 then-part
if (items[i] > items[i-1])
可以被消除,只是在序列结束时响应 (items[i] <= items[i-1]`。
Purely coding this logic:纯粹编码这个逻辑:
i
determine sequence start and endi
确定序列的开始和结束 results in:结果是:
public static void reverse(int[] items) {
for (int i = 0; i < items.length; ++i) {
int start = i;
int end = i;
while (end + 1 < items.length && items[end + 1] > items[end]) {
++end;
}
i = end;
while (start < end) {
int temp = items[start];
items[start] = items[end];
items[end] = temp;
++start;
--end;
}
}
}
One could eliminate the first while
determining the subsequence by holding state variables before the for-loop, but the above is easiest.通过在 for 循环之前保留 state 个变量,可以
while
确定子序列时消除第一个,但以上是最简单的。
The reduction in lines-of-code is from 17 LoC to 12 LoC.代码行数从 17 LoC 减少到 12 LoC。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.