Re: Quicksort
- From: "robertwessel2@xxxxxxxxx" <robertwessel2@xxxxxxxxx>
- Date: Tue, 8 Jan 2008 16:09:00 -0800 (PST)
On Jan 8, 4:58 pm, CBFalconer <cbfalco...@xxxxxxxxx> wrote:
"robertwess...@xxxxxxxxx" wrote:
CBFalconer <cbfalco...@xxxxxxxxx> wrote:
Stack size is unavoidably a problem with the fully recursive
version, unless, of course you can afford order N stack space.
Or your compiler guarantees to do tail-recursion elimination.
That won't normally control the recursion depth, since each level
has to depend on the relative size of the segments. It is
trivially easy to do it yourself, and ensure the depth never
exceeds ln2(size).
If you recurse in the correct order (smaller partition first),
and the compiler does tail recursion elimination for the second
(larger) partition, you will use no more than log(n) stack space.
Basically what's happening is that the compiler converts the
fully recursive form to the semi recursive form of quicksort by
looping on the second (larger) partition.
Write out the code and see the problem for yourself.
OK:
quicksort(partition p)
{
leftpart,rightpart=partition(p)
smallpart,largepart=orderbysize(leftpart,rightpart)
quicksort(smallpart)
quicksort(largepart)
}
What problem? If the compiler does tail recursion elimination, the
second recursive call is turned into a loop, and the only growth in
stack size happens when the smaller partition is recursively sorted,
which trivially ensures a limit of log(n) stack usage.
IOW, tail recursion elimination allows the compiler to convert the
above into the explicitly semi-recursive version of quicksort:
quicksort(partition p)
{
loop while ((size of p) > 1)
{
leftpart,rightpart=partition(p)
smallpart,largepart=orderbysize(leftpart,rightpart)
quicksort(smallpart)
p=largepart
}
}
If the compiler does *not* do tail recursion elimination, stack usage
is proportional to n in the worst case. Given that most compiler
don't actually do tail recursion elimination, and many of the ones
that do don't provide strong guarantees as to when it happens, a fully
recursive quicksort implementation (as first pseudocode sample) should
almost always be considered flawed.
.
- Follow-Ups:
- Re: Quicksort
- From: CBFalconer
- Re: Quicksort
- From: cr88192
- Re: Quicksort
- References:
- Quicksort
- From: Roman Töngi
- Re: Quicksort
- From: Adak
- Re: Quicksort
- From: robertwessel2@xxxxxxxxx
- Re: Quicksort
- From: robertwessel2@xxxxxxxxx
- Re: Quicksort
- From: CBFalconer
- Re: Quicksort
- From: robertwessel2@xxxxxxxxx
- Re: Quicksort
- From: CBFalconer
- Quicksort
- Prev by Date: Re: Quicksort
- Next by Date: Re: Article on Herbert Schildt, author of C Unleashed, repaired on wikipedia
- Previous by thread: Re: Quicksort
- Next by thread: Re: Quicksort
- Index(es):
Relevant Pages
|