Randomized Algorithms in TheAlgorithms/Java: A Complete Implementation Guide

Yes, TheAlgorithms/Java contains a dedicated com.thealgorithms.randomized package with implementations of QuickSort with random pivots, reservoir sampling, Freivalds' matrix verification, Karger's min-cut, and Monte Carlo integration.

The repository maintains a comprehensive collection of probabilistic techniques designed for educational purposes and practical application. These implementations demonstrate how randomness improves algorithmic efficiency, from avoiding worst-case performance in sorting to achieving sublinear verification for matrix multiplication.

Randomized Algorithms Package Overview

The primary home for these implementations is the com.thealgorithms.randomized package located under src/main/java/com/thealgorithms/randomized/. This module follows the utility class pattern, where most classes are declared final with private constructors that throw UnsupportedOperationException to prevent instantiation.

Core Classes and File Locations

Key Randomized Algorithm Implementations

Randomized QuickSort

In src/main/java/com/thealgorithms/randomized/RandomizedQuickSort.java, the algorithm selects a random pivot index using Math.random() to eliminate the risk of O(n²) behavior on adversarial or already-sorted inputs.

import com.thealgorithms.randomized.RandomizedQuickSort;

public class QuickSortDemo {
    public static void main(String[] args) {
        int[] data = { 9, 2, 7, 4, 1, 5 };
        RandomizedQuickSort.randomizedQuickSort(data, 0, data.length - 1);
        System.out.println(java.util.Arrays.toString(data));
    }
}

The pivot selection logic pivotIndex = low + (int)(Math.random() * (high - low + 1)) ensures uniform probability distribution across the current subarray.

Reservoir Sampling

The ReservoirSampling class in src/main/java/com/thealgorithms/randomized/ReservoirSampling.java implements the classic algorithm for selecting k random elements from a stream of unknown size using O(k) memory.

import com.thealgorithms.randomized.ReservoirSampling;
import java.util.List;

public class ReservoirDemo {
    public static void main(String[] args) {
        int[] stream = new int[1000];
        for (int i = 0; i < stream.length; i++) stream[i] = i;
        
        List<Integer> sample = ReservoirSampling.sample(stream, 10);
        System.out.println("Random sample: " + sample);
    }
}

The implementation uses Random.nextInt(i + 1) to maintain the reservoir property, replacing existing elements with decreasing probability as the stream progresses.

Freivalds' Matrix Verification

Located in src/main/java/com/thealgorithms/randomized/RandomizedMatrixMultiplicationVerification.java, this class implements Freivalds' algorithm for probabilistically verifying whether C = A × B without performing the full multiplication.

import com.thealgorithms.randomized.RandomizedMatrixMultiplicationVerification;

public class FreivaldsDemo {
    public static void main(String[] args) {
        int[][] A = {{1, 2}, {3, 4}};
        int[][] B = {{5, 6}, {7, 8}};
        int[][] C = {{19, 22}, {43, 50}};
        
        boolean likelyCorrect = RandomizedMatrixMultiplicationVerification.verify(A, B, C, 5);
        System.out.println("Verification result: " + likelyCorrect);
    }
}

With k iterations, the error probability drops to 2⁻ᵏ, providing 96.875% accuracy with the default five checks.

Other Notable Implementations

  • KargerMinCut – Implements global minimum cut for graphs via random edge contraction in O(n²) time with high probability.
  • MonteCarloIntegration – Estimates definite integrals using uniform random sampling over the function domain.
  • RandomizedClosestPair – Computes the closest pair of points in Euclidean space using random shuffling and divide-and-conquer.

Design Patterns and Architecture

The randomized algorithms in TheAlgorithms/Java follow consistent architectural principles:

  • Dependency Injection of Random – Classes like RandomScheduling accept Random instances via constructors, enabling reproducible unit tests with fixed seeds.
  • Stateless Functional API – Methods accept input arrays and return results without mutating global state, ensuring thread safety.
  • Thread-Local Randomness – Some utilities leverage ThreadLocalRandom for concurrent environments to avoid contention.

Usage in Other Packages

Randomness extends beyond the dedicated package into other algorithm categories:

  • com.thealgorithms.searches.RandomSearch – Selects random indices until locating the target element.
  • com.thealgorithms.scheduling – Contains RandomScheduling for random task ordering and LotteryScheduling for probability-based process selection.
  • com.thealgorithms.sorts.SortUtilsRandomGenerator – Centralized java.util.Random instance shared by sorting utilities including bogo-sort and randomized quick-sort variants.

Summary

  • TheAlgorithms/Java implements randomized algorithms in the com.thealgorithms.randomized package with six core classes.
  • RandomizedQuickSort uses random pivots to guarantee expected O(n log n) time complexity.
  • ReservoirSampling provides O(n) stream sampling with O(k) space complexity.
  • Freivalds' algorithm offers probabilistic matrix multiplication verification with exponentially decreasing error rates.
  • The codebase follows utility class patterns and supports dependency injection of Random instances for testability.

Frequently Asked Questions

What randomized algorithms are implemented in TheAlgorithms/Java?

The repository implements Randomized QuickSort, Reservoir Sampling, Freivalds' Matrix Verification, Randomized Closest Pair, Monte Carlo Integration, and Karger's Min-Cut in the com.thealgorithms.randomized package. Additional utilities like Random Search and Lottery Scheduling appear in other packages.

How does RandomizedQuickSort prevent worst-case O(n²) performance?

The algorithm selects pivots uniformly at random using Math.random(), making the probability of consistently poor pivot selection exponentially small. This guarantees expected O(n log n) performance even on sorted or adversarial inputs that would trigger quadratic behavior in deterministic quick-sort.

Where is the source code for reservoir sampling located?

The implementation resides in src/main/java/com/thealgorithms/randomized/ReservoirSampling.java. The class provides a static sample(int[] stream, int k) method that returns a List<Integer> containing k randomly selected elements from the input stream.

Does the repository use ThreadLocalRandom for concurrent operations?

Yes, several utilities utilize ThreadLocalRandom instead of java.util.Random to avoid synchronization overhead in multi-threaded environments. The design patterns also emphasize stateless methods and immutable inputs to support safe concurrent execution.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →