Roozilla
Roozilla

Reputation: 83

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). 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}. 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}```

Upvotes: 1

Views: 104

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

You are looking back comparing items[i] with 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]).

Also the then-part if (items[i] > items[i-1]) could be eliminated, just responding when the sequence ends (items[i] <= items[i-1]`.

Purely coding this logic:

  • at position i determine sequence start and end
  • reverse [start .. end].

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.

The reduction in lines-of-code is from 17 LoC to 12 LoC.

Upvotes: 1

Related Questions