gsl提供API以按升序对矢量进行排序,但是,我是否遗漏了按降序排序的内容?我不想要" gsl_sort_largest"创造和额外的矢量。
答案 0 :(得分:2)
如何反转排序后的矢量?与使用gsl_vector_reverse
时一样。简单的测试用例如下:
#include <stdlib.h>
#include <stdio.h>
#include <gsl/gsl_sort_float.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_vector.h>
void
pvec(const char *str, const gsl_vector *v, const int n)
{
int i = 0;
printf("%s", str);
for (i = 0; i < n; ++i) {
printf("v_%d = %g\n", i, gsl_vector_get(v, i));
}
}
int
main(int argc, char **argv)
{
int i = 0;
int n = 5;
const gsl_rng_type *T;
gsl_rng *r = NULL;
gsl_vector *v = gsl_vector_alloc(n);
T = gsl_rng_default;
r = gsl_rng_alloc(T);
for (i = 0; i < n; ++i) {
gsl_vector_set(v, i, gsl_rng_uniform(r));
}
pvec("Before sorting\n", v, n);
gsl_sort_vector(v);
pvec("\nAfter sorting\n", v, n);
gsl_vector_reverse(v);
pvec("\nAfter reversing\n", v, n);
gsl_rng_free(r);
gsl_vector_free(v);
return(EXIT_SUCCESS);
}
关于编译和运行的内容:
$ gcc -o svec svec.c -lgsl
$ ./svec
Before sorting
v_0 = 0.999742
v_1 = 0.16291
v_2 = 0.282618
v_3 = 0.947201
v_4 = 0.231657
After sorting
v_0 = 0.16291
v_1 = 0.231657
v_2 = 0.282618
v_3 = 0.947201
v_4 = 0.999742
After reversing
v_0 = 0.999742
v_1 = 0.947201
v_2 = 0.282618
v_3 = 0.231657
v_4 = 0.16291