# Randomized Algorithms in TheAlgorithms/Java: A Complete Implementation Guide

> Explore randomized algorithms in TheAlgorithms/Java. Discover implementations of QuickSort reservoir sampling Freivalds matrix verification Karger's min-cut and Monte Carlo integration.

- Repository: [The Algorithms/Java](https://github.com/TheAlgorithms/Java)
- Tags: tutorial
- Published: 2026-03-04

---

**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

- **[`RandomizedQuickSort.java`](https://github.com/TheAlgorithms/Java/blob/main/RandomizedQuickSort.java)** – Implements quick-sort with uniform random pivot selection to guarantee expected O(n log n) performance regardless of input distribution.
- **[`ReservoirSampling.java`](https://github.com/TheAlgorithms/Java/blob/main/ReservoirSampling.java)** – Provides O(n) time sampling from data streams using constant memory.
- **[`RandomizedMatrixMultiplicationVerification.java`](https://github.com/TheAlgorithms/Java/blob/main/RandomizedMatrixMultiplicationVerification.java)** – Contains Freivalds' probabilistic algorithm for verifying matrix products in O(k·n²) time versus deterministic O(n³).
- **[`RandomizedClosestPair.java`](https://github.com/TheAlgorithms/Java/blob/main/RandomizedClosestPair.java)** – Expected O(n log n) closest-pair algorithm using randomized divide-and-conquer.
- **[`MonteCarloIntegration.java`](https://github.com/TheAlgorithms/Java/blob/main/MonteCarloIntegration.java)** – Numerical integration using random sampling with configurable seeds.
- **[`KargerMinCut.java`](https://github.com/TheAlgorithms/Java/blob/main/KargerMinCut.java)** – Graph min-cut via random edge contraction.

## Key Randomized Algorithm Implementations

### Randomized QuickSort

In [`src/main/java/com/thealgorithms/randomized/RandomizedQuickSort.java`](https://github.com/TheAlgorithms/Java/blob/main/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.

```java
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`](https://github.com/TheAlgorithms/Java/blob/main/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.

```java
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`](https://github.com/TheAlgorithms/Java/blob/main/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.

```java
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`](https://github.com/TheAlgorithms/Java/blob/main/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.