1

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.

liumilan
  • 365
  • 1
  • 4
  • 13
  • Don't recurse to solve the larger part. Just recurse into the smaller part and handle the large part on the current level – Niklas B. Mar 18 '14 at 03:26
  • The main thing to realize is that a tail-recursive call doesn't increase the depth of the stack. – Vaughn Cato Mar 18 '14 at 04:14
  • Possible duplicate of [quicksort stack size](http://stackoverflow.com/questions/6709055/quicksort-stack-size) –  Mar 06 '16 at 12:47

1 Answers1

0

Think of a binary tree. Any binary tree.

Now at each node, you choose to traverse the subtree with fewer nodes, till you get to a leaf.

What is the length of the path you followed? O(log n)? Yes?

It is the same here.