[英]Sort an Array of struct by a value of a field inside the struct
I am trying to implement a GA, Genetic Algorithm and I need to do the selection stage, I have chosen first to order all individual ann s, I have the following structures我正在尝试实施 GA,遗传算法,我需要进行选择阶段,我选择首先订购所有单独的ann s,我有以下结构
typedef struct ann {
int inputs; /* Number of input neurones */
int hidden_layers; /* Number of hidden layers */
int hidden; /* Number of hidden neurones */
int outputs; /* Number of output neurons. */
int weights; /* Total nof weigths(chromosomes)*/
int neurons; /* Total Number of neurones */
double *weight; /* The weights(genotype) */
double *output; /* Output */
double fitness; /* Total fitness of the network */
double *delta;
actfun activation_hidden; /* Hidden layer activation func */
actfun activation_output; /* Output layer activation func */
} ann;
and I also have an array of this struct, like this我也有一个这个结构的数组,就像这样
ann *population = malloc ( population_size * sizeof(ann));
for( i = 0; i < population_size; i++ ){
population[i] = *create( trainset->num_inputs, 1 , hidden, trainset->num_outputs);
}
When I pass this population array to the following function当我将此人口数组传递给以下函数时
void selection(ann* an, int size)
{
int temp=0,j,i;
for(i=1;i<size;i++)
{
for(j=0;j<size-i;j++)
{
if(an[j].fitness >an[j+1].fitness)
{
printf("swaped\n");
temp=an[j].fitness;
an[j].fitness =an[j+1].fitness;
an[j+1].fitness = temp;
}
}
}
}
```
I should be getting a sorted array with ascending fitness values like
20.3, 21.4, 22.6
but i get
22.6, 18.0, 20.3
and so on when I
```
printf(" %f ", population[i].fitness);
```
My Question is how can I properly sort this array?
Here is the (link)[https://stackoverflow.com/questions/59604077/how-to-assign-an-array-of-structs]! to the question i asked before, that shows the code of function create
Is the standard library unavailable?标准库不可用吗?
#include <stdlib.h>
int compareAnn(const void* a, const void* b)
{
const ann* pa = (const ann*)a;
const ann* pb = (const ann*)b;
return pa->fitness - pb->fitness;
}
void selection(ann* an, int size)
{
qsort(an, size, sizeof(ann), compareAnn);
}
You can use the qsort()
function with a custom comparison function here.您可以在此处使用带有自定义比较函数的
qsort()
函数。 First, define the comparison function:首先定义比较函数:
int compare (const void *_a, const void *_b) {
ann *a = _a, *b = _b;
return a->fitness - b->fitness;
}
then, sort the array itself:然后,对数组本身进行排序:
qsort(an, size, sizeof(ann), compare);
This should result in the array sorted by the fitness criterion.这应该导致按适应度标准排序的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.