Quicksorting a linked list
From: Alan Morgan (amorgan_at_Xenon.Stanford.EDU)
Date: 07/28/04
- Next message: John Hanley: "return value conventions in c"
- Previous message: Paul E. Black: "Re: Strange kind of doubly-linked list"
- Next in thread: Thad Smith: "Re: Quicksorting a linked list"
- Reply: Thad Smith: "Re: Quicksorting a linked list"
- Reply: Paul E. Black: "Re: Quicksorting a linked list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 28 Jul 2004 20:59:50 +0000 (UTC)
The main problem with using quicksort to sort a linked list (that I know
of) is chosing a good pivot. If you always choose the first element then
you end up with O(n^2) worst case behavior. With an array you have more
options (median of first/middle/last or random element are popular
choices). It occurred to me that you can do the same thing with linked
lists as well.
During the partition stage you will be constructing two lists - smaller
and larger. There is a well known technique for picking a random line
from a file of unknown length. You can apply this to the two partition
lists as you build them and end up with a random element from each of
them that you can use in the next stage of the sort.
If you'd prefer to do the first/middle/last median method then you can
start off with a middle pointer that points to the beginning of the
(empty) smaller and larger lists. Advance it by one node for every
two you add and it will end up pointing to the element in the middle of
the list. Lather, rinse, recurse.
Obviously for both of these you need to pick your pivot the "hard way"
for the first pass. I don't see that as being a problem.
Any comments?
Alan
-- Defendit numerus
- Next message: John Hanley: "return value conventions in c"
- Previous message: Paul E. Black: "Re: Strange kind of doubly-linked list"
- Next in thread: Thad Smith: "Re: Quicksorting a linked list"
- Reply: Thad Smith: "Re: Quicksorting a linked list"
- Reply: Paul E. Black: "Re: Quicksorting a linked list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|