private static int Pivot(ArrayList array, int lower, int upper) { // Pivot with first element int left = lower + 1; object pivot = array[lower]; int right = upper; // Partition array elements while (left <= right) { // Find item out of place while ((left <= right) && (comparer.Compare(array[left], pivot) <= 0)) { ++left; } while ((left <= right) && (comparer.Compare(array[right], pivot) > 0)) { --right; } // Swap values if necessary if (left < right) { swapper.Swap(array, left, right); ++left; --right; } } // Move pivot element swapper.Swap(array, lower, right); return(right); }
public Log Compute(Graph graph) { TerminateCondition Terminate = this.terminateStrategy(); int numberOfRoutes = 0; //Initalise population for (int i = 0; i < population.Length; i++) { population[i] = InitalisationStrategy.Initalise(graph.nodes); } Route?bestRoute = default; Stopwatch timer = new Stopwatch(); timer.Start(); int generationCounter = 0; int itterationCounter = 0; while (!Terminate()) { Route[] parents = selectionStrategy.Select(population, 20, step); //Recombine pairs of parents Route[] children = Recombine(parents, (int)eliteism * parents.Length); //Mutate the resulting offsprint for (int i = 0; i < children.Length; i++) { if (random.NextDouble() < mutationRate) { children[i] = swap.Swap(children[i]); } numberOfRoutes++; bestRoute = bestRoute == null ? children[i] : step.CostP(children[i], bestRoute); population[generationCounter] = children[i]; generationCounter = (generationCounter + 1) % population.Length; } OnItterationComplete?.Invoke(this, new Log() { numberOfRoutesEvaluated = numberOfRoutes, iteration = itterationCounter, bestRouteCost = bestRoute != null ? bestRoute.Distance() : float.MaxValue, bestRoute = bestRoute != null ? bestRoute.ToString() : string.Empty, timeToCompute = timer.ElapsedMilliseconds, }); } timer.Stop(); return(new Log() { timeToCompute = timer.ElapsedMilliseconds, numberOfRoutesEvaluated = numberOfRoutes, iteration = itterationCounter, bestRouteCost = bestRoute != null?bestRoute.Distance() : float.MaxValue, bestRoute = bestRoute != null?bestRoute.ToString() : string.Empty, }); }