Path: utzoo!attcan!uunet!munnari.oz.au!basser!steve From: steve@basser.oz (Stephen Russell) Newsgroups: comp.lang.modula2 Subject: Re: Quicksort vs. Heapsort Message-ID: <2585@basser.oz> Date: 30 Sep 89 16:31:55 GMT References: <828zebolskyd@yvax.byu.edu> Sender: msgs@basser.oz Organization: Dept of Comp Sci, Uni of Sydney, Australia Lines: 32 In article <828zebolskyd@yvax.byu.edu> zebolskyd@yvax.byu.edu writes: >In <2033@ethz.UUCP>, Michael Rys writes: > >>In 1987 a guy called Carlson (I think) improved the Heapsort-Algorithm >>by using a binary search for inserting into the sorted list. In this >>way Heapsort is always faster than Quicksort for very larg n. > >It is interesting that it took until 1987 for somebody to make that >improvement. I was watching a demonstration program for QuickBasic >on the Macintosh that compares the various methods. The one they called >a heap sort used a linear search to insert. I thought there was a mistake or >bug, because a binary search would have been so much faster. I'm going to feel a real fool if I get this wrong, but ... since when did _anyone_ use 'linear searching' to add an element to a heap? I think there is some confusion here. For example, there is no "sorted list" in a heap, at least in the conventional sense of sorted. A "linear search" to find the "insertion" point makes no sense at all. To add an element to a heap with elements h[1] to h[n], you just add one to n, put the new element at h[n] (for new n), then compare it with h[n/2]. If h[n] > h[n/2], swap them, then compare h[n/2] with h[n/4], etc. This maintains the invariant h[k] >= max(h[k*2], h[k*2+1]) for k = 1..n/2, which is the definition of a heap. This is obviously a binary search (the divisor doubles at each iteration), and is the _only_ way to add elements to a heap. I suspect that some out there are confusing an "insertion sort" with a "heapsort". Steve Russell