2 * Implement Heap sort -- direct and indirect sorting
3 * Based on descriptions in Sedgewick "Algorithms in C"
4 * Copyright (C) 1999 Thomas Walter
6 * 18 February 2000: Modified for GSL by Brian Gough
8 * This is free software; you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation; either version 3, or (at your option) any
13 * This source is distributed in the hope that it will be useful, but WITHOUT
14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
21 #include <gsl/gsl_heapsort.h>
23 static inline void downheap (size_t * p, const void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare);
25 #define CMP(data,size,j,k) (compare((const char *)(data) + (size) * (j), (const char *)(data) + (size) * (k)))
28 downheap (size_t * p, const void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare)
30 const size_t pki = p[k];
36 if (j < N && CMP (data, size, p[j], p[j + 1]) < 0)
41 if (CMP (data, size, pki, p[j]) >= 0)
55 gsl_heapsort_index (size_t * p, const void *data, size_t count, size_t size, gsl_comparison_fn_t compare)
57 /* Sort the array in ascending order. This is a true inplace
58 algorithm with N log N operations. Worst case (an already sorted
59 array) is something like 20% slower */
65 return GSL_SUCCESS; /* No data to sort */
68 for (i = 0; i < count; i++)
70 p[i] = i ; /* set permutation to identity */
73 /* We have n_data elements, last element is at 'n_data-1', first at
74 '0' Set N to the last element number. */
79 k++; /* Compensate the first use of 'k--' */
83 downheap (p, data, size, N, k, compare);
89 /* first swap the elements */
94 /* then process the heap */
97 downheap (p, data, size, N, 0, compare);