-1

CLRS Problem : 7.4

How does Tail-Recursive-QuickSort improve the efficiency of quick sort any better ?

Original quicksort


enter image description here

Tail recursive quicksort


enter image description here

Question

Modify the code for TAIL-RECURSIVE-QUICKSORT so that the worst-case stack depth is O(n log n). Maintain the O(n log n) expected running time of the algorithm.

Answer

We are always doing a tail-recursive call on the second partition. We can modify the algorithm to do the tail recursion on the larger partition. That way, we'll consume less stack.

Both algorithms sort the both partitions. But how does the stack consume less space by operating Tail-Recursive-QuickSort on larger partition?

sagar
  • 101
  • 1
  • 2

1 Answers1

1

Quicksort may split an array of size n into two arrays of size (n-1) and 1 if you are unlucky. So a recursive call might be given an array of size (n-1) and make a recursive call with an array of size (n-2) and so on, for a maximum recursion depth of n.

Note that one of the array parts must have a size ≤ n/2. So which one do you sort by starting at the beginning of the loop, and which one do you sort by recursion?

gnasher729
  • 32,238
  • 36
  • 56