Re: Mergesort algorithm for linked lists
- From: Joerg Schoen <jo65.spammenot@xxxxxxxxx>
- Date: Sun, 28 Jan 2007 22:43:10 +0100
CBFalconer wrote:
I don't think a reverse sorted input is the worst case for
natural mergesort, but it's proportional to n log n comparisons.
(The reason reverse-sorted is not worst-case is that when you're
merging two lists, you will stop performing comparisons as soon
as one list is exhausted.)
If the occurance of pre-sorted lists is likely, you can do a
preliminary scan to decide if the list is sorted, reverse-sorted,
or unsorted. If sorted, nothing to do. If reverse sorted list
reversal is O(n). Otherwise you can accept the O(NlogN) of
mergesort. At most the preliminary test has added to the constant
factor. Your data will govern whether or not it is worthwhile.
Note that you can abandon the preliminary scan early once lack of
any sorting is detected.
As it turns out, the natural mergesort excels on a sorted list and in
general takes advantage on any preorder in the list. But even the
non-natural mergesort does well on sorted as well as reverse-sorted
lists.
The reason is given above by Googmeister: The merging stops comparisons
if one list is exhausted - the other one is simply appended.
So I believe that looking for natural runs is enough of an optimization.
Adding preliminary scans for various "pathological" cases is rather
useless for the general case.
.
- References:
- Re: Mergesort algorithm for linked lists
- From: Stephen Howe
- Re: Mergesort algorithm for linked lists
- From: pete
- Re: Mergesort algorithm for linked lists
- From: Googmeister
- Re: Mergesort algorithm for linked lists
- From: pete
- Re: Mergesort algorithm for linked lists
- From: CBFalconer
- Re: Mergesort algorithm for linked lists
- Prev by Date: Re: Mergesort algorithm for linked lists
- Next by Date: hey help in solving the following recurrence...
- Previous by thread: Re: Mergesort algorithm for linked lists
- Next by thread: Re: Mergesort algorithm for linked lists
- Index(es):
Relevant Pages
|