I'm implementing the partition function for QuickSort, and I've come across behavior that seems confusing. Specifically, in the partition logic:
int partition(int A[], int low,
int high)
{
int pivot = A[low];
int i = low + 1;
int j = high;
int temp;
do
{
while (A[i] <= pivot)
{
i++;
}
while (A[j] > pivot)
{
j--;
}
if (i < j)
{
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
} while (i < j);
// Swap A[low] and A[j]
temp = A[low];
A[low] = A[j];
A[j] = temp;
return j;
}
Here’s my concern:
When iterating through the while (A[i] <= pivot) loop, if all the elements on the left side are smaller than or equal to the pivot, i keeps incrementing until it exceeds the bounds (high).
Similarly, the while (A[j] > pivot) loop causes j to decrement when elements on the right are larger than the pivot.
If i or j cross boundaries (e.g., i > high), shouldn’t this cause the do-while loop to break unexpectedly or even enter an infinite loop?
For example, if the input array is {12, 6, 7, 9, 10}, and the pivot is 12, the i pointer would increment up to 5 (out of bounds) since all elements are less than or equal to the pivot. However, this code still works and produces a correct partition.
Question: Why does this code still work, even though i seems to exceed the bounds during the while (A[i] <= pivot) loop? How is the infinite loop avoided in this case?