I was looking at another page here on stackoverflow and came across a working implementation of cycle sort, but I don't understand how a statement with a semicolon can exist before the curly braces in a while loop. I thought that the while loop is supposed to completely terminate and take no further actions once it finds a statement with a semicolon, so how is it that the code within the curly braces is getting executed? At first glance, I would interpret this as "var" gets incremented with each iteration of the while loop - but I know this is not the case because removing it from that spot and putting the "var++" inside of the curly braces causes an infinite loop.
Under exactly which condition is "var" incremented? Either an explanation, or a link that explains similar syntax:
while (checkSomeBool) var++;
{
//other stuff happening in here
}
would be appreciated. Thank you. Below is the code taken from CycleSort
public static final > int cycleSort(final T[] array) {
int writes = 0;
// Loop through the array to find cycles to rotate.
for (int cycleStart = 0; cycleStart < array.length - 1; cycleStart++) {
T item = array[cycleStart];
// Find where to put the item.
int pos = cycleStart;
for (int i = cycleStart + 1; i < array.length; i++)
if (array[i].compareTo(item) < 0) pos++;
// If the item is already there, this is not a cycle.
if (pos == cycleStart) continue;
// Otherwise, put the item there or right after any duplicates.
{
final T temp = array[pos];
array[pos] = item;
item = temp;
}
writes++;
// Rotate the rest of the cycle.
while (pos != cycleStart) {
// Find where to put the item.
pos = cycleStart;
for (int i = cycleStart + 1; i < array.length; i++)
if (array[i].compareTo(item) < 0) pos++;
// Put the item there or right after any duplicates.
while (item.equals(array[pos])) pos++;
{
final T temp = array[pos];
array[pos] = item;
item = temp;
}
writes++;
}
}
return writes;
}
解决方案
The while loop ends with var++
while (checkSomeBool) var++; // while ends here
The code after that is not part of the while loop at all.
{
//other stuff happening in here - not part of the while loop
}