Please take a look at this snippet code from and implementation of quicksort, it’s from the book Data Structures and Problem Solving Using Java :
int i, j;
for(i = low, j = high -1;;){
while(array[++i].compareTo(pivot) < 0)
;
while(pivot.compareTo(array[--j]) < 0)
;
if(i >= j)
break;
swapReferences(array, i, j);
}
I’m having a bit of trouble understanding how this works. From my understanding the for loop just declares the starting point and doesn’t contain any rules on when to finish the for loop; that’s handled by the if statement, is that correct?
Also, without the brackets I’m not clear about the while loops. the semi-colon and lack of indentation suggested they’re not nested. But there’s no actual code within the loops.
Am I correct in saying each while is separate, one compares lower values to the pivot and one compares higher values, swapping when each of the while loops criteria are met. As the i is incremented and j is decremented every time the for loop carries on with the process until the criteria for the if statement are met at which point it breaks from the for loop?
Is this correct?
EDIT: Updated code to reflect exactly what was in the book.
Your analysis is correct. The
whileloops do their work implicitly, with++iand--j. It could be rewritten for more clarity as