Removing Tail recursions in quicksort

N

nkharan

Hey,
Here is the pseudocode of quicksort. It can be observed that there
are as many as (n-1) unresolved stack calls in the worst case. Now, how
do i reduce this unresolved stack calls? what modifications should I
make?

procedure QuickSort(L[0:n-1], low, high) recursive
Input: L[0:n-1] (a list of size n), low, high (integers)
Output: L[low:high] is sorted
if high > low then
Partition(L[0:n-1], low, high, position)
QuickSort(L[0:n-1], low, position - 1)
QuickSort(L[0:n-1], position + 1, high)
endif
end QuickSort


thanks,

Haran
 
G

Greg

Hey,
Here is the pseudocode of quicksort. It can be observed that there
are as many as (n-1) unresolved stack calls in the worst case. Now, how
do i reduce this unresolved stack calls? what modifications should I
make?

procedure QuickSort(L[0:n-1], low, high) recursive
Input: L[0:n-1] (a list of size n), low, high (integers)
Output: L[low:high] is sorted
if high > low then
Partition(L[0:n-1], low, high, position)
QuickSort(L[0:n-1], low, position - 1)
QuickSort(L[0:n-1], position + 1, high)
endif
end QuickSort

I would expect only log2(n) levels of recursion for a quicksort of n
items. So I would change the pseudocode to be a less recursive
implementation.

Greg
 
J

John Harrison

Hey,
Here is the pseudocode of quicksort. It can be observed that there
are as many as (n-1) unresolved stack calls in the worst case. Now, how
do i reduce this unresolved stack calls? what modifications should I
make?

procedure QuickSort(L[0:n-1], low, high) recursive
Input: L[0:n-1] (a list of size n), low, high (integers)
Output: L[low:high] is sorted
if high > low then
Partition(L[0:n-1], low, high, position)
QuickSort(L[0:n-1], low, position - 1)
QuickSort(L[0:n-1], position + 1, high)
endif
end QuickSort


thanks,

Haran

Obvious homework question and nothing to do with C++ either.

Obviously you weren't paying to much attention in class, had you been
you would have known to convert the tail recursive call into a loop.

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top