Kurp Kurp - 1 month ago 7
Java Question

Increment int each time the termination expression is checked in a for loop

Is it possible to increment something each time the for loop checks the termination condition? I'm trying to compare two sort algorithms for a project, and I have a increment for the number of swaps made, but I'd also like to increment something for each time it checks the termination condition on the for loop. Thanks!

Here's my code:

for(int i=1; i<array.length; i++) {
for (int j=i; (j>0) && (array[j]<(array[j-1])); j--) {
Sort.swap(array, j, j-1);
swaps++;
}
}


As said, I would like to check how many times "(j>0) && (array[j]<(array[j-1]))" is evaluated so that I may compare it to other sorting algorithms.

I've tried adding increments in the loop but it gives me errors for adding increments in the termination expression, stating that they cannot be converted to bool.

Thank you for any help!

Answer

The last clause of a for expression is evaluated every iteration. You can put more than one variable increment in that space.

for(int i=1; i<array.length; i++) {
    int checks = 0;
    for (int j=i; (j>0) && (array[j]<(array[j-1])); j--, checks++) {
        Sort.swap(array, j, j-1);
        swaps++;
    }
    System.out.println(checks);
} 
Comments