簡體   English   中英

按結構內字段的值對結構數組進行排序

[英]Sort an Array of struct by a value of a field inside the struct

我正在嘗試實施 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;

我也有一個這個結構的數組,就像這樣

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);
}

當我將此人口數組傳遞給以下函數時

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

標准庫不可用嗎?

#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);
}

您可以在此處使用帶有自定義比較函數的qsort()函數。 首先定義比較函數:

int compare (const void *_a, const void *_b) {
    ann *a = _a, *b = _b;
    return a->fitness - b->fitness;
}

然后,對數組本身進行排序:

qsort(an, size, sizeof(ann), compare);

這應該導致按適應度標准排序的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM