Loop Invariant in Recursive function

algorithm-analysisalgorithms

When I was reading Introduction to Algorithms (3rd edition, P188), there is
an algorithm called Tail-Recursive-QuickSort and we have to prove the correctness of this algorithm.

TAIL-RECURSIVE-QUICKSORT(A, p, r)
1 while p < r
2     // Partition and sort left subarray.
3     q = PARTITION(A, p, r)
4     TAIL-RECURSIVE-QUICKSORT(A, p, q - 1)
5     p = q + 1

The problem is, when I tried to use loop invariant, I found it difficult for me to explain the maintenance clearly because of the recursive function inside the loop body. The loop invariant I use is:

Before each iteration, A[0:p-1] are sorted.

The initial case is trivial, but the maintenance involves prove TAIL-RECURSIVE-QUICKSORT doesn't change loop invariant. Is there any way to explain it clearly?

Thanks.

Best Answer

Ok, perhaps the snippet is too small. I don't see the tail recursion, just a function with "TAIL" in the name.

But when a language or compiler takes advantage of tail recursion, the code runs the same as if it were not tail recursive, except for not using as much stack space.

During a tail call optimization, variable state in the current frame is replaced in its entirety with new state from the new call (just as if the new call had been made unoptimized with a new stack frame). No state from the caller survives except where to return.

So, if you can prove the normal recursive case, you can apply that proof to the tail recursive case.

Tail recursion is an optimization technique, and, optimization techniques don't change your algorithm (broken or buggy compiler notwithstanding).


As far as proving the proving the invariant regarding the recursion, I think it is an academic exercise; for example, see here: https://www.cs.rochester.edu/~gildea/csc282/slides/C07-quicksort.pdf

Before each iteration, A[0:p-1] are sorted.

I don't think there is quicksort invariant that requires the input is sorted, but rather that it is partitioned, which is a testable condition but not the same as sorted.

Further, a recursive quicksort, a the top-level, doesn't operate in terms of iterations, as there is no outer loop, but in terms of invocations as there is recursion.

Related Topic