Now I was reading introduction to algorithms, Quicksort chapter. It said that tail recursion can be used for optimization.
QUICKSORT'(A, p, r)
while p < r
do ▸ Partition and sort left subarray.
q ← PARTITION(A, p, r)
QUICKSORT'(A, p, q - 1)
p ← q + 1
But the stack depth of above code will be O(n) if the pivot number is [1,n-1] [n] on every iteration.
QUICKSORT (A, p, r )
while p < r
do Partition and sort the small subarray Þrst
q ← PARTITION(A, p, r )
if q − p < r − q
then QUICKSORT (A, p, q − 1)
p ← q + 1
else QUICKSORT (A, q + 1, r )
r ← q − 1
What I understand in code above is that it will handle subarray with smaller length first. But why it can be reduced to O(lgn)? If the pivot is still [1,n-1] [n] every time,I think it keeps O(n) stack depth.