nextupprevious
Next:9.6 Quick SortUp:9. Sorting MethodsPrevious:9.4 Shellsort

9.5 Heap Sort

Worst case as well as average case running time is O(nlog n)
REF.
Robert W. Floyd. Algorithm 245 (TreeSort). Communications of the ACM, Volume 7, pp. 701, 1964.
REF.
J.W.J. Williams. Algorithm 232 (Heapsort). Communications of the ACM, Volume 7, pp. 347-348, 1964.

    {

            Insert all records to form a heap S;

            while (S is not empty)

                {

                    y = min (S);

                    print the value of y;

                    delete y from S;

                }

    }


Heap sort crucially uses a function called pushdown (first, last).

This assumes that the elements a[first], a[first + 1], ..., a[last] obey the heap property, except possibly the children of a[first]. The function pushes a[first] down until the heap property is restored.

Example: See Figure 9.2. Here, a[1],..., a[10] is a heap except that the children of a[1]violate the heap property.

Figure 9.2: Illustration of some heap operations
\begin{figure}\centerline{\psfig{figure=figures/Fheap3.ps,width=5in}}\end{figure}

Heapsort Algorithm

    {

            for$ \left(\vphantom{i = \frac{n}{2}, i >= 1; i--}\right.$i$ {\frac{n}{2}}$, i > = 1;i - -$ \left.\vphantom{i = \frac{n}{2}, i >= 1; i--}\right)$

                    pushdown (i, n); /* initial heap construction */

            for($ \underline{i = n;}$ i > = 2;i - -)

            {

            swap records a[i] and a[1];

            pushdown (1, i - 1)

            }

    }


nextupprevious
Next:9.6 Quick SortUp:9. Sorting MethodsPrevious:9.4 Shellsort
eEL,CSA_Dept,IISc,Bangalore