Reputation: 143
As part of an experiment with genetic learning algorithms, it would be useful to be able to sort an entire array of 'genes' into fitness order. So far the only answers I can find in the community deal with the highest, or second highest values and so forth.
Has anyone developed a robust array sorting method that could be implemented in C++? It seems a lot of implementation involve the ( int i : array) method which is not universally accepted by all C++ platforms.
I would be grateful for any assistance.
Upvotes: 0
Views: 323
Reputation: 2739
Why not use std::sort
as defined in <algorithm>
? See here. You can also define a custom comparator.
Sample usage is as follows
std::sort(someArray,someArray+lengthOfArray);
std::sort(someVector.begin(),someVector.end());
stable_sort
also exists, if you need it.
The custom comparator can be useful if fitness is not a straight <
operator (eg involving some simulation). Then you can do something like this
struct {
bool operator()(gene a, gene b)
{
// However you compare genes for fitness. Not specific code,
// just an example.
a.simulateLife();
b.simulateLife();
return a.fitness < b.fitness;
}
} geneCompare;
std::sort(genes.begin(),genes.end(),geneCompare);
In addition, perhaps you do not need to sort the whole array. If for example, only 20 out of 100 genes survive the timestep, you only want the first 20 values. In this case std::partial_sort
is your friend. More info here.
Upvotes: 10