/** * This class represents a population for the GA. * It also contains the fitness function and * a quicksort algorithm to sort the individuals. * * coding: h.sarg * modified: 01/98 */ public class Population { /** * array which holds the individuals of the population */ private Individual[] pop; /** * best fitness in the population */ private double bestfit; /** * number of the best individual */ private int bestindex; /** * mean fitness of the population */ private double meanfit; /** * population size */ private int popsize; /** * length of the genstring */ private int size; /** * Object which holds the information about the towns */ private TravelData travel; /** * This constructor creates a new population. * @param travel object which contains the values of the towns * @param popsize population size * @param size number of towns * @param init indicates if the population should be initialized */ public Population(TravelData travel, int popsize, int size, int init) { int i; this.travel = travel; this.popsize = popsize; this.size = size; bestfit = -1; bestindex = -1; meanfit = -1; pop = new Individual[popsize]; if(init == 1) { for(i=0; i=fit) { best=fit; bestindex=i; } } bestfit=best; } /** * interface to the quicksort algorithm to determine the number of * the individuals and to get the mean value */ public void qsort() { int i; double mean=0.0; quicksort(0, popsize-1); for(i=0; i lo0) { /* Arbitrarily establishing partition element as the midpoint of * the array. */ mid = pop[ ( lo0 + hi0 ) / 2 ].getFitness(); // loop through the array until indices cross while( lo <= hi ) { /* find the first element that is greater than or equal to * the partition element starting from the left Index. */ while( ( lo < hi0 ) && ( pop[lo].getFitness() < mid )) ++lo; /* find an element that is smaller than or equal to * the partition element starting from the right Index. */ while( ( hi > lo0 ) && ( pop[hi].getFitness() > mid )) --hi; // if the indexes have not crossed, swap if( lo <= hi ) { swap(lo, hi); ++lo; --hi; } } /* If the right index has not reached the left side of array * must now sort the left partition. */ if( lo0 < hi ) quicksort(lo0, hi ); /* If the left index has not reached the right side of array * must now sort the right partition. */ if( lo < hi0 ) quicksort(lo, hi0 ); } } /** * swap the individual i withe the individual j * @param i position i * @param j position j */ private void swap(int i, int j) { Individual T; T = pop[i]; pop[i] = pop[j]; pop[j] = T; } }