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

> Explore over 20 search algorithm implementations in TheAlgorithms/Java. Discover binary search, graph traversals, and more in this comprehensive guide. Get started today.

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

---

**The TheAlgorithms/Java repository hosts over 20 production-ready search algorithm implementations, ranging from classic binary search and linear scan methods to advanced graph traversals and probabilistic techniques, all organized under the `src/main/java/com/thealgorithms/searches/` package.**

TheAlgorithms/Java is one of the most comprehensive open-source collections of computer science algorithms available today. The search algorithms module provides type-safe, generic implementations for locating elements in arrays, matrices, graphs, and text strings. Every array-based algorithm adheres to a common contract defined by the `SearchAlgorithm` interface, ensuring consistent APIs across diverse searching strategies.

## Unified Interface for Array Searches

At the architectural core of the repository lies the **`SearchAlgorithm`** interface located at [`src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java`](https://github.com/TheAlgorithms/Java/blob/main/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java). This generic contract standardizes how array-based searches operate across the codebase.

Classes implementing this interface expose the uniform method signature:

```java
<T extends Comparable<T>> int find(T[] array, T key)

```

The method returns the zero-based **index** of the matching element, or **-1** when the key is absent from the array. This design allows seamless substitution of algorithms without changing client code, supporting any type that implements `Comparable` such as `Integer`, `String`, or custom domain objects.

## Linear and Binary Search Variants

The repository provides multiple implementations of fundamental searching techniques, each optimized for specific scenarios.

**LinearSearch** offers the simplest approach, scanning elements sequentially until finding a match or reaching the array end. For scenarios requiring boundary optimization, **SentinelLinearSearch** eliminates bounds checking overhead by placing the target value at the array's end as a sentinel.

For sorted data, the binary search family provides logarithmic **O(log n)** performance:

- **BinarySearch**: Classic recursive divide-and-conquer implementation in [`src/main/java/com/thealgorithms/searches/BinarySearch.java`](https://github.com/TheAlgorithms/Java/blob/main/src/main/java/com/thealgorithms/searches/BinarySearch.java)
- **IterativeBinarySearch**: Non-recursive stack-friendly variant
- **OrderAgnosticBinarySearch**: Automatically detects ascending or descending sort order before searching
- **RotatedBinarySearch**: Handles circularly shifted sorted arrays (e.g., `[4, 5, 1, 2, 3]`)
- **SquareRootBinarySearch**: Locates integer square roots using binary search principles

## Interpolation and Jump Search Techniques

Beyond standard binary search, the repository includes algorithms that exploit data distribution characteristics.

**InterpolationSearch** estimates the probable position of the target value using linear interpolation between array endpoints. Note that unlike other implementations, this class specifically operates on primitive `int[]` arrays rather than generic `Comparable` types.

**JumpSearch** balances between linear and binary approaches, checking elements at intervals of √N before performing a linear backtrack within the identified block. This achieves **O(√n)** complexity without the overhead of recursive calls.

Additional specialized array searches include:

- **TernarySearch** and **IterativeTernarySearch**: Divide ranges into three segments rather than two
- **ExponentialSearch**: Doubles the search interval until exceeding the target, then binary searches within the bounded range
- **FibonacciSearch**: Uses Fibonacci numbers to partition the search space, minimizing comparison operations for certain access patterns

## Graph Traversal and Probabilistic Methods

For non-linear data structures, the repository provides fundamentally different search paradigms that do not implement the `SearchAlgorithm` interface but instead expose domain-specific APIs.

**DepthFirstSearch** and **BreadthFirstSearch** in `src/main/java/com/thealgorithms/searches/` provide adjacency matrix traversal capabilities. These classes implement `traverse()` methods rather than `find()`, visiting vertices according to stack-based (DFS) or queue-based (BFS) disciplines.

Probabilistic approaches include:

- **RandomSearch**: Monte Carlo-style random probing for unstructured search spaces
- **MonteCarloTreeSearch**: Full MCTS implementation for game AI and decision-making scenarios

## String Matching and Matrix Search

Text processing algorithms implement specialized search contracts optimized for string data.

**BoyerMoore** implements the classic Boyer-Moore bad-character heuristic for substring searching, delivering sub-linear performance on large alphabets. **RabinKarpAlgorithm** provides rolling-hash based pattern matching with average-case linear complexity.

For information retrieval contexts, **BM25InvertedIndex** implements the Okapi BM25 ranking function commonly used in search engines.

Two-dimensional search capabilities include:

- **SearchInARowAndColWiseSortedMatrix**: Locates elements in matrices where each row and column is individually sorted
- **BinarySearch2dArray** and **RowColumnWiseSorted2dArrayBinarySearch**: Variants optimized for strictly sorted 2D structures

## Utility and Selection Algorithms

The repository includes helper classes for statistical queries and bound calculations.

**LowerBound** and **UpperBound** implement standard C++-style bound queries, returning the first index where the target could be inserted without violating sort order. **QuickSelect** provides average-case linear time selection of the k-th smallest element, useful for computing medians and order statistics without full sorting.

## Practical Implementation Examples

### Binary Search on Generic Arrays

```java
import com.thealgorithms.searches.BinarySearch;

public class Demo {
    public static void main(String[] args) {
        Integer[] numbers = {1, 3, 5, 7, 9, 11};
        int index = new BinarySearch().find(numbers, 7);   // → 3
        System.out.println("Found at index: " + index);
    }
}

```

*Implementation*: [[`BinarySearch.java`](https://github.com/TheAlgorithms/Java/blob/main/BinarySearch.java)](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/BinarySearch.java)

### Linear Search on Strings

```java
import com.thealgorithms.searches.LinearSearch;

String[] words = {"apple", "banana", "cherry"};
int pos = new LinearSearch().find(words, "banana"); // → 1

```

*Implementation*: [[`LinearSearch.java`](https://github.com/TheAlgorithms/Java/blob/main/LinearSearch.java)](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/LinearSearch.java)

### Jump Search on Sorted Integers

```java
import com.thealgorithms.searches.JumpSearch;

Integer[] sorted = {2, 4, 6, 8, 10, 12, 14, 16};
int idx = new JumpSearch().find(sorted, 10); // → 4

```

*Implementation*: [[`JumpSearch.java`](https://github.com/TheAlgorithms/Java/blob/main/JumpSearch.java)](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/JumpSearch.java)

### Interpolation Search for Uniform Data

```java
import com.thealgorithms.searches.InterpolationSearch;

int[] data = {10, 20, 30, 40, 50};
int result = new InterpolationSearch().find(data, 30); // → 2

```

*Implementation*: [[`InterpolationSearch.java`](https://github.com/TheAlgorithms/Java/blob/main/InterpolationSearch.java)](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/InterpolationSearch.java)

### Depth-First Graph Traversal

```java
import com.thealgorithms.searches.DepthFirstSearch;

int[][] adjacency = {
    {0,1,0},
    {1,0,1},
    {0,1,0}
};
DepthFirstSearch dfs = new DepthFirstSearch();
dfs.traverse(adjacency, 0);  // visits vertices 0 → 1 → 2

```

*Implementation*: [[`DepthFirstSearch.java`](https://github.com/TheAlgorithms/Java/blob/main/DepthFirstSearch.java)](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/DepthFirstSearch.java)

## Testing and Project Structure

All search implementations reside under `src/main/java/com/thealgorithms/searches/` with corresponding unit tests located in `src/test/java/com/thealgorithms/searches/`. This parallel structure ensures every algorithm includes JUnit verification of edge cases, boundary conditions, and performance characteristics.

The generic design utilizing `Comparable<T>` types enables immediate reuse across primitive wrappers and complex domain objects, while the consistent `find()` interface facilitates algorithm substitution during performance optimization or A/B testing scenarios.

## Summary

- TheAlgorithms/Java provides **20+ search algorithm implementations** covering arrays, graphs, strings, and matrices
- **Array-based searches** implement the uniform `SearchAlgorithm` interface with method signature `<T extends Comparable<T>> int find(T[] array, T key)`
- **Binary search variants** include classic, iterative, rotated array, and order-agnostic implementations for diverse sorted data scenarios
- **Specialized techniques** such as Jump Search, Interpolation Search, and Ternary Search offer alternatives optimized for specific data distributions
- **Graph algorithms** (DFS/BFS) and **string matchers** (Boyer-Moore, Rabin-Karp) provide domain-specific APIs for non-array structures
- All implementations include comprehensive unit tests in `src/test/java/com/thealgorithms/searches/`

## Frequently Asked Questions

### What interface do the array search algorithms implement in TheAlgorithms/Java?

Array-based search classes implement the **`SearchAlgorithm`** interface defined in [`src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java`](https://github.com/TheAlgorithms/Java/blob/main/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java). This contract requires implementing the method `<T extends Comparable<T>> int find(T[] array, T key)`, which returns the element index or -1 if not found.

### How do I search a rotated sorted array using this repository?

Use the **RotatedBinarySearch** class located at [`src/main/java/com/thealgorithms/searches/RotatedBinarySearch.java`](https://github.com/TheAlgorithms/Java/blob/main/src/main/java/com/thealgorithms/searches/RotatedBinarySearch.java). This implementation automatically handles circularly shifted arrays (where the sorted sequence wraps around) while maintaining O(log n) time complexity by determining which half of the split contains the properly ordered sequence.

### Are these search algorithms limited to primitive types like int and String?

No, the implementations are **generic**. Any class implementing `Comparable<T>` works with the standard search algorithms. For example, you can search arrays of `LocalDate`, custom `Employee` objects (implementing `Comparable<Employee>`), or `BigDecimal` values. The notable exception is **InterpolationSearch**, which specifically requires primitive `int[]` arrays due to its mathematical position-estimation formula.

### Where can I find the unit tests for these search implementations?

All unit tests reside in the parallel test directory **`src/test/java/com/thealgorithms/searches/`**, mirroring the main source structure. Each algorithm class has a corresponding JUnit test class (e.g., [`BinarySearchTest.java`](https://github.com/TheAlgorithms/Java/blob/main/BinarySearchTest.java) for [`BinarySearch.java`](https://github.com/TheAlgorithms/Java/blob/main/BinarySearch.java)) that validates correctness across empty arrays, single elements, missing values, and large datasets.