home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!darwin.sura.net!Sirius.dfn.de!Urmel.Informatik.RWTH-Aachen.DE!messua!dak
- From: dak@messua.informatik.rwth-aachen.de (David Kastrup)
- Subject: Re: Making qsort type-safe
- Message-ID: <dak.721261218@messua>
- Sender: news@Urmel.Informatik.RWTH-Aachen.DE (Newsfiles Owner)
- Nntp-Posting-Host: messua
- Organization: Rechnerbetrieb Informatik / RWTH Aachen
- References: <1992Nov4.162131.10289@cs.brown.edu> <1992Nov5.125947.1@vax1.bham.ac.uk> <1992Nov5.160048.15113@bcrka451.bnr.ca> <1992Nov6.202732.27007@mprgate.mpr.ca>
- Date: 8 Nov 92 22:20:18 GMT
- Lines: 31
-
- walduck@mpr.ca (Andrew Walduck) writes:
-
-
- >It is precisely due to this behaviour that I prefer heapsort to quicksort...
- >Quicksort performance can rapidly approach O(N^2) as the list becomes closer
- >to being sorted!! (It depends how the pivot is chosen...)
-
- >Many people think of qsort as an O(nlogn) sort...it isn't. Its average
- >case is O(nlogn)...but its worst case is O(n^2) (the same as a bubble
- >sort!!) This behaviour, when combined with its stack requirements, is
- >why I prefer heap sort. In all cases, it performs as an O(nlogn) sort...
- >and it can be implemented in 2 success loops...(about 30 lines of code
- >or so...)
-
- Quicksort needs some tuning to get really good. Fisrt, you should use
- the median 3 algorithm for choosing your pivot, and take the median of
- first, middle, and last element. That way, presorted data will partition
- perfectly. In addition, the O(n^2) worst case becomes REALLY improbable.
-
- Secondly, you should look which of the two partitions you get has less
- elements and sort that partition first in recursion. THEN sort the second,
- larger size partition by a tail recursion. That way, your stack space
- will be strictly O(lg n) even in worst case.
-
- If you are sorting linked lists, however, use a mergesort, which combines
- sorting a sublist with scanning to the head of the next sublist.
-
- Short code, guaranteed LESS than n lg n comparisons, guaranteed at most
- lg n recursion depth, no data copying, etc. And you need no tricks (as
- opposed to quicksort) to let it work well behavedly. Beats average quicksorts
- by a factor of more than 2 (at least in Turbo C it does.)
-