0

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.

5
  • Not sure what you got from result, but sorting in general re-arranges all the elements in increasing/decreasing order Commented Oct 3, 2014 at 8:58
  • 2
    cplusplus.com/reference/cstdlib/qsort cplusplus.com/reference/algorithm/sort cplusplus.com/reference/algorithm/stable_sort ... And there are plenty more on the internet Commented Oct 3, 2014 at 8:58
  • 7
    std::sort perhaps ? Commented Oct 3, 2014 at 8:58
  • 1
    As @JonathanPotter says, for raw arrays you can use std::sort(std::begin(arr), std::end(arr));. Commented Oct 3, 2014 at 9:05
  • Many thanks, that's a great help - I am new to C++. Commented Oct 3, 2014 at 9:06

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wonderful, thank you. I came across nothing like this in various algorithm textbooks so thanks!
The custom comparator is a bit suspect. Evaluating fitness that way may cause intransitive results. I.e. gene a < gene b, gene b < c but also gene c < gene a. std::sort cannot handle that.
Right. But it is useful to see an example. Will update the comparator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.