gsl_sort__sortvecind_source.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Implement Heap sort -- direct and indirect sorting
  3. * Based on descriptions in Sedgewick "Algorithms in C"
  4. *
  5. * Copyright (C) 1999 Thomas Walter
  6. *
  7. * 18 February 2000: Modified for GSL by Brian Gough
  8. *
  9. * This is free software; you can redistribute it and/or modify it
  10. * under the terms of the GNU General Public License as published by the
  11. * Free Software Foundation; either version 3, or (at your option) any
  12. * later version.
  13. *
  14. * This source is distributed in the hope that it will be useful, but WITHOUT
  15. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  16. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  17. * for more details.
  18. */
  19. static inline void FUNCTION (index, downheap) (size_t * p, const BASE * data, const size_t stride, const size_t N, size_t k);
  20. static inline void
  21. FUNCTION (index, downheap) (size_t * p, const BASE * data, const size_t stride, const size_t N, size_t k)
  22. {
  23. const size_t pki = p[k];
  24. while (k <= N / 2)
  25. {
  26. size_t j = 2 * k;
  27. if (j < N && data[p[j] * stride] < data[p[j + 1] * stride])
  28. {
  29. j++;
  30. }
  31. if (!(data[pki * stride] < data[p[j] * stride])) /* avoid infinite loop if nan */
  32. {
  33. break;
  34. }
  35. p[k] = p[j];
  36. k = j;
  37. }
  38. p[k] = pki;
  39. }
  40. void
  41. FUNCTION (gsl_sort, index) (size_t * p, const BASE * data, const size_t stride, const size_t n)
  42. {
  43. size_t N;
  44. size_t i, k;
  45. if (n == 0)
  46. {
  47. return; /* No data to sort */
  48. }
  49. /* set permutation to identity */
  50. for (i = 0 ; i < n ; i++)
  51. {
  52. p[i] = i ;
  53. }
  54. /* We have n_data elements, last element is at 'n_data-1', first at
  55. '0' Set N to the last element number. */
  56. N = n - 1;
  57. k = N / 2;
  58. k++; /* Compensate the first use of 'k--' */
  59. do
  60. {
  61. k--;
  62. FUNCTION (index, downheap) (p, data, stride, N, k);
  63. }
  64. while (k > 0);
  65. while (N > 0)
  66. {
  67. /* first swap the elements */
  68. size_t tmp = p[0];
  69. p[0] = p[N];
  70. p[N] = tmp;
  71. /* then process the heap */
  72. N--;
  73. FUNCTION (index, downheap) (p, data, stride, N, 0);
  74. }
  75. }
  76. int
  77. FUNCTION (gsl_sort_vector, index) (gsl_permutation * permutation, const TYPE (gsl_vector) * v)
  78. {
  79. if (permutation->size != v->size)
  80. {
  81. GSL_ERROR ("permutation and vector lengths are not equal", GSL_EBADLEN);
  82. }
  83. FUNCTION (gsl_sort, index) (permutation->data, v->data, v->stride, v->size) ;
  84. return GSL_SUCCESS ;
  85. }