Did you notice the outer loop, loop forever
?
Let us say in the first iteration of that loop forever
loop, we have just finished the second inner loop, do j := j - 1 while A[j] > pivot
.
If
j := j-1
has been executed at least twice, thenj <= (hi+1)-2 = hi-1
.Otherwise
j := j-1
has been executed exactly once. Then
$\quad\quad$j = (hi+1)-1 = hi
.
Note that the first inner loop,do i := i + 1 while A[i] < pivot
produces
$\quad\quad$i = lo
sincei = lo - 1
initially andA[lo] = pivot
.Now we execute
if i >= j then return j
. Since the conditioni >= j
does not hold sinceaslo < hi
(onlythe pseudocode for quicksort specifies that only whenlo < hi
shall we perform partition be performed), so the codereturn j
will be skipped, i.e., we willshall go on with the next iteration of thatloop forever
loop. In that next iteration,j := j-1
will be executed again, causingj < hi
.
So, we will always have j < hi
at some point of time during the partition. Since j
would never increase, we will have j < hhi
when we return j
. $\quad\checkmark$
The analysis above holds regardless of whether our pivot is the max number or not.