Greedy and Genetic Algorithms for the 0/1 Knapsack Problem

Companion to Lectures 20 and 21

Author
Affiliations

Marcel Turcotte

School of Electrical Engineering and Computer Science

University of Ottawa

Published

November 22, 2026

This self-study notebook accompanies Lecture 20 and Lecture 21. It contains the complete greedy and genetic-algorithm implementations used in those presentations, followed by a small reproducible comparison. It runs independently of the lecture notebooks.

Problem

The 0/1 knapsack problem gives each item a weight and a value. Select items to maximize total value without exceeding a fixed capacity. Each item is either included once or excluded.

Attribution: Generated by DALL-E, via ChatGPT (GPT-4), OpenAI, November 10, 2024.

The main comparison uses one fixed instance. The appendix retains the procedure for studying the original collection of 25 benchmark instances.

Data and setup

The following instance comes from Google OR-Tools. A candidate is a binary array: entry i indicates whether item i is selected.

Code
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

values = np.array([
    360, 83, 59, 130, 431, 67, 230, 52, 93, 125, 670, 892, 600, 38, 48, 147,
    78, 256, 63, 17, 120, 164, 432, 35, 92, 110, 22, 42, 50, 323, 514, 28,
    87, 73, 78, 15, 26, 78, 210, 36, 85, 189, 274, 43, 33, 10, 19, 389, 276,
    312])

weights = np.array([
    7, 0, 30, 22, 80, 94, 11, 81, 70, 64, 59, 18, 0, 36, 3, 8, 15, 42, 9, 0,
    42, 47, 52, 32, 26, 48, 55, 6, 29, 84, 2, 4, 18, 56, 7, 29, 93, 44, 71,
    3, 86, 66, 31, 65, 0, 79, 20, 65, 52, 13])

capacity = 850

Greedy baselines

Each method sorts the items, then considers them in that order and includes an item if it fits:

  • By weight: lightest items first.
  • By value: most valuable items first.
  • By value-to-weight ratio: largest ratios first, taking positive-value zero-weight items first.

These are deterministic baselines, not guarantees of an optimal 0/1 solution. Skipping an item that does not fit still leaves the possibility of including a later item. Ratio sorting solves the fractional variant under its usual assumptions, but the indivisible-item problem is different.

Code
def greedy_knapsack_weight(weights, values, capacity):
    """Consider lighter items first; return a feasible binary solution."""
    items = sorted(zip(weights, values, range(len(weights))))
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for weight, value, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight


def greedy_knapsack_value(weights, values, capacity):
    """Consider more valuable items first, skipping those that do not fit."""
    items = sorted(zip(values, weights, range(len(weights))), reverse=True)
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for value, weight, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight


def greedy_knapsack_ratio(weights, values, capacity):
    """Consider value/weight ratios, taking positive-value free items first."""
    ratios = np.divide(values, weights, out=np.full(len(weights), np.inf),
                       where=weights != 0)
    items = sorted(zip(ratios, values, weights, range(len(weights))), reverse=True)
    solution = np.zeros(len(weights), dtype=int)
    total_value, total_weight = 0, 0
    for ratio, value, weight, index in items:
        if total_weight + weight <= capacity:
            solution[index] = 1
            total_weight += weight
            total_value += value
    return solution, total_value, total_weight
greedy_methods = {
    "Greedy by weight": greedy_knapsack_weight,
    "Greedy by value": greedy_knapsack_value,
    "Greedy by ratio": greedy_knapsack_ratio,
}
greedy_rows = []
for name, method in greedy_methods.items():
    solution, value, weight = method(weights, values, capacity)
    greedy_rows.append({"Method": name, "Value": value, "Weight": weight})
greedy_results = pd.DataFrame(greedy_rows)
greedy_results
Method Value Weight
0 Greedy by weight 5891 817
1 Greedy by value 7339 849
2 Greedy by ratio 7534 850

Genetic algorithm

The implementation below uses the same components as the presentations. The binary representation does not impose the capacity constraint. A penalty gives overweight candidates a selection score, while a separate incumbent retains the best feasible solution encountered. The empty knapsack provides a feasible initial incumbent.

The returned value and weight describe that feasible incumbent. The fitness histories describe the population’s selection scores, which may include penalized, infeasible candidates. They contain the initial population at generation 0 and every completed generation, including the last.

All stochastic operations receive the same numpy.random.Generator within a run. Create a new generator for each independent run.

Code
def initialize_population(pop_size, num_items, rng):
    """Generate random binary candidates; feasibility is assessed separately."""
    return rng.integers(2, size=(pop_size, num_items))


def evaluate_fitness(population, weights, values, capacity, penalty_factor=10):
    """Score candidates for selection; a finite penalty does not enforce capacity."""
    total_weights = population @ weights
    total_values = population @ values
    penalties = penalty_factor * np.maximum(0, total_weights - capacity)
    return total_values - penalties


def roulette_selection(population, fitness, rng):
    """Sample parents with replacement, proportional to shifted fitness."""
    adjusted_fitness = fitness - np.min(fitness) + 1e-6
    probabilities = adjusted_fitness / np.sum(adjusted_fitness)
    selected_indices = rng.choice(len(population), size=len(population),
                                  replace=True, p=probabilities)
    return population[selected_indices]


def tournament_selection(population, fitness, tournament_size, rng):
    """Select one winner per tournament; larger scores are better here."""
    selected_indices = []
    for _ in range(len(population)):
        participants = rng.choice(len(population), tournament_size, replace=False)
        winner = participants[np.argmax(fitness[participants])]
        selected_indices.append(winner)
    return population[selected_indices]


def single_point_crossover(parents, crossover_rate, rng):
    """Recombine binary parents, returning the same number of offspring."""
    num_parents, num_genes = parents.shape
    parents = parents[rng.permutation(num_parents)]
    offspring = []
    for i in range(0, num_parents, 2):
        parent1 = parents[i]
        parent2 = parents[(i + 1) % num_parents]
        child1, child2 = parent1.copy(), parent2.copy()
        if num_genes > 1 and rng.random() < crossover_rate:
            point = rng.integers(1, num_genes)
            child1[:point], child2[:point] = parent2[:point], parent1[:point]
        offspring.extend((child1, child2))
    return np.array(offspring[:num_parents])


def uniform_crossover(parents, crossover_rate, rng):
    """Choose independently which parent supplies each binary gene."""
    num_parents, num_genes = parents.shape
    parents = parents[rng.permutation(num_parents)]
    offspring = []
    for i in range(0, num_parents, 2):
        parent1 = parents[i]
        parent2 = parents[(i + 1) % num_parents]
        child1, child2 = parent1.copy(), parent2.copy()
        if rng.random() < crossover_rate:
            mask = rng.integers(2, size=num_genes).astype(bool)
            child1[mask], child2[mask] = parent2[mask], parent1[mask]
        offspring.extend((child1, child2))
    return np.array(offspring[:num_parents])


def mutation(offspring, mutation_rate, rng):
    """Flip each bit independently with the specified per-gene probability."""
    mutation_matrix = rng.random(offspring.shape) < mutation_rate
    offspring[mutation_matrix] = 1 - offspring[mutation_matrix]
    return offspring


def elitism(population, fitness, elite_size):
    """Copy the highest-scoring individuals into the next population."""
    if elite_size == 0:
        return population[:0].copy()
    elite_indices = np.argsort(fitness)[-elite_size:]
    return population[elite_indices].copy()
Code
def genetic_algorithm(weights, values, capacity, *, rng, pop_size=100,
                      num_generations=100, crossover_rate=0.8,
                      mutation_rate=0.05, elite_percent=0.02,
                      selection_type='roulette', tournament_size=3,
                      crossover_type='single_point', penalty_factor=10):
    """Run one binary GA and return its best feasible solution and fitness traces.

    Histories contain generations 0 through num_generations. The population
    budget is pop_size * (num_generations + 1) fitness evaluations. All item
    values and weights are nonnegative; the empty knapsack is feasible.
    """
    population = initialize_population(pop_size, len(weights), rng)
    elite_size = int(pop_size * elite_percent)
    best_solution = np.zeros(len(weights), dtype=int)
    best_value, best_weight = 0, 0
    average_fitness_history, best_fitness_history = [], []

    for generation in range(num_generations + 1):
        fitness = evaluate_fitness(population, weights, values, capacity,
                                   penalty_factor)
        average_fitness_history.append(float(np.mean(fitness)))
        best_fitness_history.append(float(np.max(fitness)))

        # Selection scores may favor overweight candidates. Keep a feasible
        # incumbent by actual value, independently of the selection policy.
        total_weights = population @ weights
        total_values = population @ values
        feasible_indices = np.flatnonzero(total_weights <= capacity)
        if len(feasible_indices) > 0:
            index = feasible_indices[np.argmax(total_values[feasible_indices])]
            if total_values[index] > best_value:
                best_solution = population[index].copy()
                best_value = total_values[index]
                best_weight = total_weights[index]

        if generation == num_generations:
            break  # The final population has been evaluated and recorded.

        elites = elitism(population, fitness, elite_size)
        if selection_type == 'roulette':
            parents = roulette_selection(population, fitness, rng)
        elif selection_type == 'tournament':
            parents = tournament_selection(population, fitness, tournament_size, rng)
        else:
            raise ValueError("Choose 'roulette' or 'tournament' selection.")

        if crossover_type == 'single_point':
            offspring = single_point_crossover(parents, crossover_rate, rng)
        elif crossover_type == 'uniform':
            offspring = uniform_crossover(parents, crossover_rate, rng)
        else:
            raise ValueError("Choose 'single_point' or 'uniform' crossover.")
        offspring = mutation(offspring, mutation_rate, rng)
        population = np.vstack((elites, offspring[:pop_size - elite_size]))

    return (best_solution, best_value, best_weight,
            average_fitness_history, best_fitness_history)

One reproducible run

This run uses tournament selection and single-point crossover. For binary chromosomes, mutation_rate is a probability per bit. This differs from Assignment 4’s probability of applying inversion per offspring.

With population size P and G generations, the implementation evaluates P(G+1) candidates, including the initial population. Keeping the best feasible solution and recording traces does not introduce additional independent searches.

pop_size = 100
num_generations = 100
run_settings = dict(
    pop_size=pop_size, num_generations=num_generations,
    crossover_rate=0.8, mutation_rate=0.05, elite_percent=0.02,
    selection_type="tournament", tournament_size=3,
    crossover_type="single_point",
)

example_result = genetic_algorithm(
    weights, values, capacity, rng=np.random.default_rng(4106), **run_settings)
solution, value, weight, average_history, best_history = example_result
print("Best feasible solution:", solution)
print("Value:", value)
print("Weight:", weight, "/", capacity)
print("Fitness evaluations:", pop_size * (num_generations + 1))
Best feasible solution: [1 1 0 1 1 0 1 0 0 0 1 1 1 0 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 1 0 0
 0 1 1 0 0 1 0 1 0 0 1 1 1]
Value: 7497
Weight: 841 / 850
Fitness evaluations: 10100
Code
def plot_fitness_over_generations(avg_fitness_history, best_fitness_history):
    """Show selection scores, including generation 0 and the final population."""
    generations = np.arange(len(avg_fitness_history))
    plt.figure(figsize=(6, 5))
    plt.plot(generations, avg_fitness_history, label='Mean selection fitness')
    plt.plot(generations, best_fitness_history, label='Maximum selection fitness')
    plt.xlabel('Generation')
    plt.ylabel('Penalized fitness')
    plt.title('Selection Fitness over Generations')
    plt.legend()
    plt.tight_layout()
    plt.show()

plot_fitness_over_generations(average_history, best_history)

The maximum selection fitness need not equal the best feasible value: selection can favor an overweight candidate with a modest penalty. Retaining the feasible incumbent ensures that the reported answer respects capacity even in that case.

Repeated runs

One seed gives one trajectory. The following five independent runs keep the instance, settings, and per-run evaluation budget fixed. The first result is reused from the plotted run, so only four additional searches are needed. Greedy methods are deterministic and are therefore executed once per instance.

seeds = [4106, 4107, 4108, 4109, 4110]
solution, value, weight, average_history, best_history = example_result
run_rows = [{
    "Seed": seeds[0], "Value": value, "Weight": weight,
    "Fitness evaluations": pop_size * (num_generations + 1),
}]
for seed in seeds[1:]:
    solution, value, weight, average_history, best_history = genetic_algorithm(
        weights, values, capacity, rng=np.random.default_rng(seed), **run_settings)
    run_rows.append({
        "Seed": seed, "Value": value, "Weight": weight,
        "Fitness evaluations": pop_size * (num_generations + 1),
    })
run_results = pd.DataFrame(run_rows)
run_results
Seed Value Weight Fitness evaluations
0 4106 7497 841 10100
1 4107 7434 850 10100
2 4108 7526 848 10100
3 4109 7496 850 10100
4 4110 7493 847 10100
Code
run_values = run_results["Value"].to_numpy()
q1, median, q3 = np.quantile(run_values, [0.25, 0.5, 0.75])
print(f"Median feasible value: {median:.1f}")
print(f"Interquartile range: {q3 - q1:.1f}")
print(f"Best-of-{len(seeds)} feasible value: {np.max(run_values)}")
print("Total fitness evaluations across these runs:",
      int(run_results["Fitness evaluations"].sum()))

fig, ax = plt.subplots(figsize=(7, 4))
ax.scatter(np.arange(1, len(seeds) + 1), run_values, label="GA runs", zorder=3)
for row in greedy_rows:
    ax.axhline(row["Value"], linestyle="--", label=row["Method"])
ax.set_xticks(np.arange(1, len(seeds) + 1), labels=seeds)
ax.set_xlabel("Run seed")
ax.set_ylabel("Feasible knapsack value")
ax.set_title("Five GA Runs and Deterministic Greedy Baselines")
ax.legend()
fig.tight_layout()
plt.show()
Median feasible value: 7496.0
Interquartile range: 4.0
Best-of-5 feasible value: 7526
Total fitness evaluations across these runs: 50500

The best-of-five value consumes five run budgets. It should be identified separately from the median single-run performance. These observations concern this instance and this configuration; they do not establish that GA always outperforms greedy methods.

Questions to investigate

  1. Does a high selection-fitness score guarantee feasibility? Which result does the algorithm actually return?
  2. How much variation is visible across seeds? Would reporting only the strongest run change the impression given by the results?
  3. If the population doubles while the fitness-evaluation budget stays fixed, how should the number of generations change?
  4. Does the ordering used by a greedy baseline explain which items it misses?

For configuration comparisons, use the same seed list and change one setting at a time. Choose settings on development instances before evaluating their transfer to other instances.

Resources

Appendix

Additional benchmark instances

The original collection from Donald Kreher’s knapsack data page contains 25 instances of different sizes. The code below downloads an instance only when no local copy is available, runs each greedy baseline once, and records a separate GA result for each seed.

The benchmark is manual because it combines downloads and many runs. Set RUN_BENCHMARK to True to execute it. It caches instance files in knapsack-data and writes a new knapsack_benchmark_seeded.csv, leaving older output files intact. An ordinary Run All executes the main example without downloading this collection.

Code
from pathlib import Path
import requests

BASE_URL = "https://pages.mtu.edu/~kreher/cages/data/knapsack/"

def read_knapsack_data(filename, cache_dir=Path("knapsack-data")):
    """Read a cached benchmark instance, downloading it on first use."""
    path = cache_dir / filename
    if not path.exists():
        response = requests.get(BASE_URL + filename, timeout=30)
        response.raise_for_status()
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(response.text)
    lines = path.read_text().strip().splitlines()
    num_items = int(lines[0])
    values = np.array(list(map(int, lines[1].split())))
    weights = np.array(list(map(int, lines[2].split())))
    capacity = int(lines[3])
    if len(values) != num_items or len(weights) != num_items:
        raise ValueError("The instance's item count does not match its data.")
    return values, weights, capacity


def benchmark_instances(filenames, seeds, run_settings):
    """Return deterministic baselines and individual seeded GA runs."""
    rows = []
    evaluations = run_settings["pop_size"] * (run_settings["num_generations"] + 1)
    for filename in filenames:
        values, weights, capacity = read_knapsack_data(filename)
        for name, method in greedy_methods.items():
            solution, value, weight = method(weights, values, capacity)
            rows.append({
                "Instance": filename, "Method": name, "Seed": None,
                "Value": value, "Weight": weight, "Capacity": capacity,
                "GA fitness evaluations": None,
            })
        for seed in seeds:
            solution, value, weight, average_history, best_history = genetic_algorithm(
                weights, values, capacity, rng=np.random.default_rng(seed), **run_settings)
            rows.append({
                "Instance": filename, "Method": "GA", "Seed": seed,
                "Value": value, "Weight": weight, "Capacity": capacity,
                "GA fitness evaluations": evaluations,
            })
    return pd.DataFrame(rows)
Code
datasets = [
    "ks_8a.dat", "ks_8b.dat", "ks_8c.dat", "ks_8d.dat", "ks_8e.dat",
    "ks_12a.dat", "ks_12b.dat", "ks_12c.dat", "ks_12d.dat", "ks_12e.dat",
    "ks_16a.dat", "ks_16b.dat", "ks_16c.dat", "ks_16d.dat", "ks_16e.dat",
    "ks_20a.dat", "ks_20b.dat", "ks_20c.dat", "ks_20d.dat", "ks_20e.dat",
    "ks_24a.dat", "ks_24b.dat", "ks_24c.dat", "ks_24d.dat", "ks_24e.dat",
]
RUN_BENCHMARK = False

if RUN_BENCHMARK:
    benchmark_results = benchmark_instances(datasets, seeds, run_settings)
    benchmark_results.to_csv("knapsack_benchmark_seeded.csv", index=False)
    print(benchmark_results.groupby(["Instance", "Method"])["Value"].agg(
        ["count", "median", "min", "max"]))

Compare algorithms within each instance rather than averaging raw values across differently scaled instances. Report GA distributions and evaluation budgets; greedy sorting and a GA fitness evaluation are different operations, so the GA evaluation column is not a measure of greedy computational work. A broad superiority claim requires an explicit comparison protocol and evidence from more than one winning run.