/*
 * @(#)HeapSortAlgorithm.java   1.0 95/06/23 Jason Harrison
 *
 * Copyright (c) 1995 University of British Columbia
 *
 * Permission to use, copy, modify, and distribute this software
 * and its documentation for NON-COMMERCIAL purposes and without
 * fee is hereby granted provided that this copyright notice
 * appears in all copies. Please refer to the file "copyright.html"
 * for further important copyright and licensing information.
 *
 * UBC MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. UBC SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

/** A heap sort demonstration algorithm. <br />
 *  <br />
 *  Author Jason Harrison, his version 1.0, 23 Jun 1995<br />
 *  <br />
 *  Modif. 15.11.2005, Albrecht Weinert (a-weinert.de) :<br />
 *  {@link SortApplet.SortAlgorithm} + Kleinigkeiten.<br />  
 *  <br />
 *  @author   Albrecht Weinert
 *  @version  V.161, 28.05.2011
 */
public final class HeapSortAlgorithm extends SortApplet.SortAlgorithm {

   @Override void sort(int[] a) {
      int n = a.length;
      for (int k = n/2; k > 0; k--) {
         downheap(a, k, n);
         pause(k, n); //  k, n von A.W.
      }
      do {
         int top = a[0];
         a[0] = a[n - 1];
         a[n - 1] = top;
         n = n - 1;
         pause(n);
         downheap(a, 1, n);
      } while (n > 1);
   } // sort(int[])
   
   void downheap(int[] a, int k, int n)  {
      int temp = a[k - 1];
      while (k <= n/2) {
         int j = k + k;
         if ((j < n) && (a[j - 1] < a[j])) {
            j++;
         }
         if (temp >= a[j - 1]) break;
         a[k - 1] = a[j - 1];
         k = j;
         pause(k, j); // k, j von A.W.
      }
      a[k - 1] = temp;
      pause();
   } // downheap(int[], int, int) 
   
} // class HeapSortAlgorithm (15.11., 27.11.2005, A. W.)


