gsl_sort__sortind.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. * Implement Heap sort -- direct and indirect sorting
  3. * Based on descriptions in Sedgewick "Algorithms in C"
  4. * Copyright (C) 1999 Thomas Walter
  5. *
  6. * 18 February 2000: Modified for GSL by Brian Gough
  7. *
  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
  11. * later version.
  12. *
  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
  16. * for more details.
  17. */
  18. #include "gsl__config.h"
  19. #include <stdlib.h>
  20. #include "gsl_heapsort.h"
  21. 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);
  22. #define CMP(data,size,j,k) (compare((const char *)(data) + (size) * (j), (const char *)(data) + (size) * (k)))
  23. static inline void
  24. downheap (size_t * p, const void *data, const size_t size, const size_t N, size_t k, gsl_comparison_fn_t compare)
  25. {
  26. const size_t pki = p[k];
  27. while (k <= N / 2)
  28. {
  29. size_t j = 2 * k;
  30. if (j < N && CMP (data, size, p[j], p[j + 1]) < 0)
  31. {
  32. j++;
  33. }
  34. if (CMP (data, size, pki, p[j]) >= 0)
  35. {
  36. break;
  37. }
  38. p[k] = p[j];
  39. k = j;
  40. }
  41. p[k] = pki;
  42. }
  43. int
  44. gsl_heapsort_index (size_t * p, const void *data, size_t count, size_t size, gsl_comparison_fn_t compare)
  45. {
  46. /* Sort the array in ascending order. This is a true inplace
  47. algorithm with N log N operations. Worst case (an already sorted
  48. array) is something like 20% slower */
  49. size_t i, k, N;
  50. if (count == 0)
  51. {
  52. return GSL_SUCCESS; /* No data to sort */
  53. }
  54. for (i = 0; i < count; i++)
  55. {
  56. p[i] = i ; /* set permutation to identity */
  57. }
  58. /* We have n_data elements, last element is at 'n_data-1', first at
  59. '0' Set N to the last element number. */
  60. N = count - 1;
  61. k = N / 2;
  62. k++; /* Compensate the first use of 'k--' */
  63. do
  64. {
  65. k--;
  66. downheap (p, data, size, N, k, compare);
  67. }
  68. while (k > 0);
  69. while (N > 0)
  70. {
  71. /* first swap the elements */
  72. size_t tmp = p[0];
  73. p[0] = p[N];
  74. p[N] = tmp;
  75. /* then process the heap */
  76. N--;
  77. downheap (p, data, size, N, 0, compare);
  78. }
  79. return GSL_SUCCESS;
  80. }