/*
  File name: heap.c
  Created by: Ljubomir Buturovic
  Created: 09/24/2002
  Purpose: implementation of heapsort.
*/

/*
  Copyright 2004 Ljubomir J. Buturovic

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation files
  (the "Software"), to deal in the Software without restriction,
  including without limitation the rights to use, copy, modify, merge,
  publish, distribute, sublicense, and/or sell copies of the Software,
  and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#include <stdlib.h>
#include "heap.h"

static char rcsid[] = "$Id: heap.c,v 1.25 2005/04/05 05:52:44 ljubomir Exp $";

static int heap_malloc(int **idx, int **tidx, int len)
{
  int status = 0;

  if (len > 0)
    {
      *idx = calloc(len, sizeof(int));
      if (*idx != (int *) 0)
	{
	  *tidx = calloc(len, sizeof(int));
	  if (*idx == (int *) 0)
	    {
	      free(*idx);
	      status = -1;
	    }
	}
      else 
	status = -1;
    }
  return status;
}

/*
  Sifting function for fheap(). Corresponds to steps H4 - H8 in Knuth
  (see reference below).
*/
static void siftup(float *vector, int l, float value, int r, int *idx, int iel)
{
  int   i;
  int   j;
  int   done;

  j = l;
  done = 0;
  while (done == 0)
    {
      i = j;
      j += j+1;
      if (j > r)
	done = 1;
      else
	{
	  /*
	    Compare the next element with the bigger of its two
	    neighbors to the right.
	  */
	  if ((j < r) && (vector[j] < vector[j+1]))
	    j++;
	  if (value < vector[j])
	    {
	      vector[i] = vector[j];
	      if (idx != (int *) 0)
		idx[i] = idx[j];
	    }
	  else
	    done = 1;
	}
    }
  vector[i] = value;
  if (idx != (int *) 0)
    idx[i] = iel;
}

/*
  Sifting function for dheap(). 
*/
static void dsiftup(double *vector, int l, float value, int r, int *idx, int iel)
{
  int   i;
  int   j;
  int   done;

  j = l;
  done = 0;
  while (done == 0)
    {
      i = j;
      j += j+1;
      if (j > r)
	done = 1;
      else
	{
	  /*
	    Compare the next element with the bigger of its two
	    neighbors to the right.
	  */
	  if ((j < r) && (vector[j] < vector[j+1]))
	    j++;
	  if (value < vector[j])
	    {
	      vector[i] = vector[j];
	      if (idx != (int *) 0)
		idx[i] = idx[j];
	    }
	  else
	    done = 1;
	}
    }
  vector[i] = value;
  if (idx != (int *) 0)
    idx[i] = iel;
}

/*
  In-place sort for floating-point 'vector' of length 'len', in
  ascending order.

  The function returns locations of the original numbers after sorting
  if 'index' is not NULL.  For example, if smallest element in
  'vector' is originally in location 5, after sorting index[5] will be
  0. If next-smallest is originally in location 2, index[2] will be 1,
  etc.

  To produce an alternative index, indicating which element goes into
  a given location after sorting, use the following code segment:

	  for (j = 0; j < len; j++)
	    {
	      idx = index[j];
	      isx[idx] = j;
	    }


  Return -1 if 'index' is not NULL, and malloc() fails. Otherwise
  return 0.

  The heapsort algorithm works by first arranging the array into a
  'heap' order. Example heap order for an array of 8 elements a[0..7]:

     a[0] >= a[1]
     a[0] >= a[2]
     a[1] >= a[3]
     a[1] >= a[4]
     a[2] >= a[5]
     a[2] >= a[6]
     a[3] >= a[7]

  Once in heap order, the array is sorted using similar algorithm
  which produced the heap order.

  The algorithm implementation largely follows Algorithm H (Heapsort),
  in: Donald E. Knuth, The Art of Computer Programming, Volume 3,
  Second Edition, Section 5.2.3, p. 145.  Section 8.3,
  Heapsort. Addison-Wesley, 1998.

  Performance comparison for fheap(), sedgsesort() and qsort(), on a
  500 MHz Pentium laptop (times in seconds):

  length     fheap()    sedgesort()    qsort()

  1,000,000     6           2             5
  10,000,000   79          24            37

  In other words, use this function only if you need the index values.  
*/
int fheap(float *vector, int len, int **index)
{
  int   status;
  int   hdx;
  int   ndx;
  int   iel;
  float value;
  int   *idx = (int *) 0;
  int   *tidx;

  iel = 0;
  status = 0;
  if (index != (int **) 0)
    status = heap_malloc(&idx, &tidx, len);
  if ((status == 0) && (len >= 2))
    {
      if (index != (int **) 0)
	/*
	  idx[i] is the position of the current element i in the
	  original (unsorted) vector.
	*/
	for (hdx = 0; hdx < len; hdx++)
	  idx[hdx] = hdx;
      if (status == 0)
	{
	  /*
	    Rearrange 'vector' into a heap.
	  */      
	  ndx = len/2;
	  while (ndx > 0)
	    {
	      ndx--;
	      /* 
		 vector[ndx] is next element to be placed in the proper heap order.
	      */
	      value = vector[ndx];
	      iel = ndx;
	      siftup(vector, ndx, value, len-1, idx, iel);
	    }
	  /*
	    Sort the heap.
	  */
	  ndx = len-1;
	  while (ndx >= 0)
	    {
	      value = vector[ndx];
	      vector[ndx] = vector[0];
	      if (index != (int **) 0)
		{
		  iel = idx[ndx];
		  idx[ndx] = idx[0];
		}
	      ndx--;
	      if (ndx == 0)
		{
		  vector[0] = value;
		  if (index != (int **) 0)
		    idx[0] = iel;
		}
	      else
		siftup(vector, 0, value, ndx, idx, iel);
	    }
	  if (index != (int **) 0)
	    {
	      /*
		tidx[i] is the position of the original element i in
		the sorted vector.
	       */
	      for (hdx = 0; hdx < len; hdx++)
		{
		  ndx = idx[hdx];
		  tidx[ndx] = hdx;
		}
	      *index = tidx;
	      free(idx);
	    }
	}
    }
  else if (status == 0)
    {
      if (index != (int **) 0)
	*index = tidx;
      free(idx);
    }
  return status;
}

/*
  In-place sort for double 'vector' of length 'len', in
  ascending order.
*/
int dheap(double *vector, int len, int **index)
{
  int    status;
  int    hdx;
  int    ndx;
  int    iel;
  double value;
  int    *idx = (int *) 0;
  int    *tidx;

  status = 0;
  iel = 0;
  if (index != (int **) 0)
    status = heap_malloc(&idx, &tidx, len);
  if ((status == 0) && (len >= 2))
    {
      if (index != (int **) 0)
	/*
	  idx[i] is the position of the current element i in the
	  original (unsorted) vector.
	*/
	for (hdx = 0; hdx < len; hdx++)
	  idx[hdx] = hdx;
      if (status == 0)
	{
	  /*
	    Rearrange 'vector' into a heap.
	  */      
	  ndx = len/2;
	  while (ndx > 0)
	    {
	      ndx--;
	      /* 
		 vector[ndx] is next element to be placed in the proper heap order.
	      */
	      value = vector[ndx];
	      iel = ndx;
	      dsiftup(vector, ndx, value, len-1, idx, iel);
	    }
	  /*
	    Sort the heap.
	  */
	  ndx = len-1;
	  while (ndx >= 0)
	    {
	      value = vector[ndx];
	      vector[ndx] = vector[0];
	      if (index != (int **) 0)
		{
		  iel = idx[ndx];
		  idx[ndx] = idx[0];
		}
	      ndx--;
	      if (ndx == 0)
		{
		  vector[0] = value;
		  if (index != (int **) 0)
		    idx[0] = iel;
		}
	      else
		dsiftup(vector, 0, value, ndx, idx, iel);
	    }
	  if (index != (int **) 0)
	    {
	      /*
		tidx[i] is the position of the original element i in
		the sorted vector.
	       */
	      for (hdx = 0; hdx < len; hdx++)
		{
		  ndx = idx[hdx];
		  tidx[ndx] = hdx;
		}
	      *index = tidx;
	      free(idx);
	    }
	}
    }
  else if (status == 0)
    {
      if (index != (int **) 0)
	*index = tidx;
      free(idx);
    }
  return status;
}



syntax highlighted by Code2HTML, v. 0.9.1