No, you don't actually need to sort them. You are exactly correct that it will have no effect if the higher-ranked members are grouped together or not (at least with a good random number generator :) ).

Your intuition is dead on here - statistically, it will have no effect to sort, and as you mention, you don't have to waste a bunch of time and effort sorting things!

The population does not need to be sorted at all - the key to roulette selection is that the probability of a given individual being selected for reproduction is proportional to its fitness.

Say you have an unsorted population, with fitnesses as follows:

```
[12, 45, 76, 32, 54, 21]
```

To perform roulette selection, you need only pick a random number in the range 0 to 240 (the sum of the population's fitness). Then, starting at the first element in the list, subtract each individual's fitness until the random number is less than or equal to zero. So, in the above case, if we randomly pick 112, we do the following:

```
Step 1: 112 - 12 = 100. This is > 0, so continue.
Step 2: 100 - 45 = 55. This is > 0, so continue.
Step 3: 55 - 76 = -21. This is <= 0, so stop.
```

Therefore, we select individual #3 for reproduction. Note how this doesn't require the population to be sorted at all.

So, in pseudocode, it boils down to:

```
let s = sum of population fitness
let r = random number in range [0, s].
let i = 0.
while r > 0 do:
r = r - fitness of individual #i
increment i
select individual #i - 1 for reproduction.
```

Note that the `- 1`

in the final line is to counteract the `increment i`

that's done within the last iteration of the loop (because even though we've found the individual we want, it increments regardless).

## Best Solution

In tournament selection the selected individuals are not removed from the population. You may select the same individuals to take part in multiple tournaments.

Having looked at your code a little closer, I see you do have another misunderstanding. You would not typically mutate/crossover all members of the tournament. Instead, you perform a tournament, with the winner of that tournament being select as an individual to undergo mutation/crossover. This means that for mutation your tournament size must be at least 2, and for crossover the size must be at least 3 with the best 2 winning (or you can perform 2 separate tournaments to choose each of the parents to crossover).

Some pseudo-code might help: