1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
|
/* sort/subsetind_source.c
*
* Copyright (C) 1999,2000,2001 Thomas Walter, Brian Gough
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 3, or (at your option) any
* later version.
*
* This source is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*/
/* find the k-th smallest elements of the vector data, in ascending order */
int
FUNCTION (gsl_sort, smallest_index) (size_t * p, const size_t k,
const BASE * src, const size_t stride,
const size_t n)
{
size_t i, j;
BASE xbound;
if (k > n)
{
GSL_ERROR ("subset length k exceeds vector length n", GSL_EINVAL);
}
if (k == 0 || n == 0)
{
return GSL_SUCCESS;
}
/* take the first element */
j = 1;
xbound = src[0 * stride];
p[0] = 0;
/* examine the remaining elements */
for (i = 1; i < n; i++)
{
size_t i1;
BASE xi = src[i * stride];
if (j < k)
{
j++;
}
else if (xi >= xbound)
{
continue;
}
for (i1 = j - 1; i1 > 0 ; i1--)
{
if (xi > src[p[i1 - 1] * stride])
break;
p[i1] = p[i1 - 1];
}
p[i1] = i;
xbound = src[p[j-1] * stride];
}
return GSL_SUCCESS;
}
int
FUNCTION (gsl_sort_vector,smallest_index) (size_t * p, const size_t k,
const TYPE (gsl_vector) * v)
{
return FUNCTION (gsl_sort, smallest_index) (p, k, v->data, v->stride, v->size);
}
int
FUNCTION (gsl_sort, largest_index) (size_t * p, const size_t k,
const BASE * src, const size_t stride,
const size_t n)
{
size_t i, j;
BASE xbound;
if (k > n)
{
GSL_ERROR ("subset length k exceeds vector length n", GSL_EINVAL);
}
if (k == 0 || n == 0)
{
return GSL_SUCCESS;
}
/* take the first element */
j = 1;
xbound = src[0 * stride];
p[0] = 0;
/* examine the remaining elements */
for (i = 1; i < n; i++)
{
size_t i1;
BASE xi = src[i * stride];
if (j < k)
{
j++;
}
else if (xi <= xbound)
{
continue;
}
for (i1 = j - 1; i1 > 0 ; i1--)
{
if (xi < src[stride * p[i1 - 1]])
break;
p[i1] = p[i1 - 1];
}
p[i1] = i;
xbound = src[stride * p[j-1]];
}
return GSL_SUCCESS;
}
int
FUNCTION (gsl_sort_vector,largest_index) (size_t * p, const size_t k,
const TYPE (gsl_vector) * v)
{
return FUNCTION (gsl_sort, largest_index) (p, k, v->data, v->stride, v->size);
}
|