Home Search
Post
Cancel
Search | SEG

Search

You should be comfortable with Java arrays, loops, and methods. Data Structures, Sorting and Recursion, and Big O Notation provide the background used here.

Search is the process of finding information that meets a condition within a collection or a set of possible states. The result may be a matching item, its location, a path to it, or a conclusion that no match exists.

For example, an application may search a product list for an identifier, a dictionary for a word, or a network of connected locations for a route. Each problem has three ingredients: the candidates we could examine, the condition that identifies an answer, and a rule for deciding which candidate to examine next.

Consider finding product identifier 9 in [14, 3, 9, 3]. We can inspect the values one by one until we reach 9. If the identifiers are sorted, we can use their order to eliminate groups of candidates instead. The goal stays the same, but the organization of the data changes how we can reach an answer.

A search must also explain when it is finished. Finding one matching item may be enough for an exact lookup. Reporting that an item is absent requires accounting for every remaining candidate, either by inspecting it or by proving that it cannot match. This makes search a question of correctness as well as speed.

This post develops that idea through linear and binary search on arrays, then considers when other data structures or graph traversal are a better fit.

What are Search characteristics?

Search algorithms differ in what counts as a match, what they assume about the input, and how much work they do to find an answer. These characteristics are connected: an algorithm can eliminate candidates quickly only when the data gives it a valid reason to do so.

Matching and result rules

Before choosing an algorithm, define its contract. Our methods accept a non-null integer array and a target value. They return a zero-based index containing that target, or -1 when the target is absent. They do not modify the array.

Duplicates need a policy. Linear search below returns the first occurrence because it scans from the beginning. Our basic binary search returns any matching index. Both satisfy the contract, but callers cannot assume they choose the same duplicate.

For [14, 3, 9, 3], searching for 3 can validly return 1 or 3 under an “any match” contract. An API promising the first occurrence must return 1. Searching for 8 must return -1.

Input organization

Unordered data gives us no positional clue about where a value might be. Sorted data adds a useful relationship between positions and values, while a hash table organizes entries by key and a graph organizes them by connections. The algorithm must respect the structure it searches.

For the array examples below, a comparison tells us whether an inspected integer is smaller than, equal to, or larger than the target. Linear search needs only equality; binary search also uses relative order to exclude part of the array.

Linear search compares elements one at a time until it finds a match or reaches the end. It works on unordered data because it never eliminates an element without inspecting it.

For [14, 3, 9, 3] and target 9, compare 14, then 3, then 9 and return index 2. For target 8, all four comparisons fail, so the method returns -1.

The reasoning is simple: before each iteration, every earlier element has been checked and does not match. When we reach the end, no unexamined candidates remain. This persistent fact is a loop invariant.

Linear search takes O(n) time in the worst case and O(1) extra space. A match at the first position takes O(1) time; an absent target requires examining all n elements. It is often a good choice for a small collection or a single query against unordered data.

Binary search requires sorted data. For ascending integers, every value to the left of an inspected position is no greater than the value at that position, and every value to its right is no smaller.

If the middle value is smaller than the target, neither it nor anything to its left can match. If it is larger, neither it nor anything to its right can match. Each comparison discards roughly half the remaining candidates.

flowchart TB
    A["Candidate interval"] --> B{"Interval empty?"}
    B -->|"Yes"| C["Return absent"]
    B -->|"No"| D["Inspect middle element"]
    D --> E{"Compare with target"}
    E -->|"Equal"| F["Return middle index"]
    E -->|"Smaller"| G["Keep right half"]
    E -->|"Larger"| H["Keep left half"]
    G --> B
    H --> B

We will represent the candidate interval as [low, high): low is included and high is excluded. Initially low = 0 and high = values.length, covering the entire array. When low == high, the interval contains no elements.

The invariant is: if a match exists, at least one matching index lies inside the candidate interval. We preserve it by discarding only positions whose values cannot match. Every unsuccessful iteration strictly reduces the interval’s length, so the loop must terminate.

Binary search performs O(log n) comparisons for nonempty arrays, uses O(1) extra space in this iterative form, and can return on its first comparison. The time bound assumes O(1) indexed access and constant-time integer comparisons. Repeatedly finding the middle of a linked list requires traversal, so the array time bound does not transfer directly to linked storage.

Binary search assumes the array is already sorted. Checking this before every query would itself take O(n) time. Establish ordering when preparing the data and preserve it when data changes.

Boundaries and duplicates

An empty collection has no candidates. A one-element collection requires at most one comparison. Targets outside the stored value range must produce an absent result, and repeated values require a clear first-match, any-match, or all-matches policy. We will exercise these cases in the implementation rather than treating them as separate algorithms.

Search in action - code examples

We will use both strategies to search integer arrays without modifying them. The linear method follows the array from left to right. The binary method keeps the half-open candidate interval introduced above and narrows it after each comparison.

Trace the binary-search interval

We will search the ascending array [3, 7, 11, 15, 19, 23, 27] for 19. Array indexes start at 0, so these values occupy indexes 0 through 6. The interval records the indexes still under consideration. In [low, high), the square bracket means include low, and the parenthesis means exclude high. Thus [0, 7) covers the whole array; 7 marks the boundary just past it. Later, [4, 7) covers indexes 4, 5, and 6, while [4, 5) contains only index 4.

Read the table from top to bottom, with one comparison per row. The first column shows the interval before that comparison. The second gives the middle index and the value stored there. The last shows which boundary changes, producing the interval in the next row, or returns the matching index to finish the search.

Interval before comparisonMiddle index and valueNext step
[0, 7)3, value 1515 < 19, so set low = 4
[4, 7)5, value 2323 > 19, so set high = 5
[4, 5)4, value 19Return index 4

Now search for missing value 18. The first two comparisons are the same. In [4, 5), value 19 is too large, so high becomes 4. The interval [4, 4) is empty; return -1.

Notice the asymmetric updates: low = middle + 1, but high = middle. Both exclude the inspected middle because high itself is already excluded. Mixing inclusive and exclusive bounds is a common source of missed values and infinite loops.

Complete Java implementations

The midpoint expression low + (high - low) / 2 avoids the potential integer overflow of (low + high) / 2. It rounds down, selecting a valid candidate whenever low < high.

Save this as SearchAlgorithms.java, then run javac SearchAlgorithms.java and java SearchAlgorithms:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class SearchAlgorithms {
    public static int linearSearch(int[] values, int target) {
        for (int i = 0; i < values.length; i++) {
            if (values[i] == target) {
                return i;
            }
        }
        return -1;
    }

    // Precondition: values is sorted in ascending order.
    public static int binarySearch(int[] values, int target) {
        int low = 0;
        int high = values.length; // Exclusive upper bound.

        while (low < high) {
            int middle = low + (high - low) / 2;
            if (values[middle] < target) {
                low = middle + 1;
            } else if (values[middle] > target) {
                high = middle;
            } else {
                return middle;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] unordered = {14, 3, 9, 3};
        int[] ordered = {3, 7, 11, 15, 19, 23, 27};
        System.out.println(linearSearch(unordered, 9)); // 2
        System.out.println(binarySearch(ordered, 19)); // 4
        System.out.println(binarySearch(ordered, 18)); // -1
        System.out.println(binarySearch(ordered, 3));  // 0
        System.out.println(binarySearch(ordered, 27)); // 6
        System.out.println(binarySearch(new int[0], 3)); // -1
        System.out.println(binarySearch(new int[]{7}, 7)); // 0
        System.out.println(binarySearch(new int[]{7}, 6)); // -1
    }
}

An empty array starts with an empty interval, so the loop never reads an element. A single-element array is either matched or eliminated in one iteration. The same logic handles targets below the smallest element or above the largest.

The first three lines printed are 2, 4, and -1: linear search finds 9 at index 2, binary search finds 19 at index 4, and the search for 18 exhausts its candidate interval. The remaining lines exercise the first and last positions, an empty array, and single-element arrays:

1
2
3
4
5
6
7
8
2
4
-1
0
6
-1
0
-1

For the successful search, compare the code’s updates to the trace: low becomes 4, then high becomes 5, and the next midpoint is the matching index 4. For the missing value, high finally becomes 4; low < high is false, so returning -1 is justified because no candidates remain.

Duplicate handling and Java’s library

With [3, 7, 7, 7, 11], our binary search returns index 2, while linear search returns 1. If you need the first duplicate, a useful variation is lower bound: find the first index whose value is greater than or equal to the target.

Keep the same half-open interval. When values[middle] < target, move low right. Otherwise, move high to middle, even for equality, to keep looking for an earlier boundary. At termination, low is that boundary or the array length. A match exists only if low < values.length and values[low] == target. For the duplicate array and target 7, the boundary is index 1; for target 8, it is index 4, but that value is 11, so 8 is absent.

Production Java code can use java.util.Arrays.binarySearch. It requires ascending order for int[] and does not promise which duplicate it finds. Its absence result differs from our method: it returns -(insertionPoint) - 1, where the insertion point places a missing key in sorted order. Searching our seven-element array for 18 returns -5, encoding insertion point 4. Decode a negative result with -result - 1; do not test only for -1. See the official Arrays API.

What problems can Search solve?

Exact lookup is useful when checking whether an identifier exists, locating a configuration value, or detecting whether a collection already contains an item. The appropriate strategy depends on how the data is stored and how often it changes.

Choose a strategy for repeated lookups

Sorting an unordered array solely for one search usually adds unnecessary work. A scan costs O(n); preparing data with an O(n log n) comparison sort and then searching costs O(n log n) overall.

For q queries over a stable array, scanning costs O(qn) in the worst case. Sorting once and performing binary searches costs O(n log n + q log n), assuming an O(n log n) sort. Repeated queries can justify the preparation. Constants, collection size, and updates still matter: inserting into the middle of a sorted array may require O(n) shifts.

Sorting also changes positions. If callers need indices from the original array, retain an index mapping or sort records containing both the value and original position. Searching a sorted copy returns a position in that copy.

Data and query needsUseful starting choiceReason
One search in unordered dataLinear scanNo preparation required
Repeated searches in sorted array dataBinary searchLogarithmic lookup and compact storage
Frequent exact-key lookups and updatesHash tableExpected constant-time key operations under suitable hashing
Ordered lookups with frequent updatesBalanced search treeO(log n) search and updates while preserving order

Hashtables explains the assumptions behind expected constant-time lookup. A hash table does not directly provide neighboring keys or sorted ranges. A binary search tree can support ordered queries, but an unbalanced tree can degrade to linear height; the logarithmic guarantee requires balancing.

Find connections and paths

Array lookup is one form of search. In a graph, the question may be whether a node is reachable or which path connects two nodes. There may be no ordering that lets us discard half the graph by comparing keys.

Breadth-first search uses a queue to explore nodes by distance in edges from a starting node. It finds shortest paths by edge count in an unweighted graph. Depth-first search follows a branch before returning to alternatives, using an explicit stack or recursive calls. Both need visited-state tracking when cycles are possible. With adjacency lists, each takes O(V + E) time to explore the reachable portion, where V counts visited vertices and E counts examined edges.

Conclusion

Search connects a question about data to a systematic way of examining candidates. Define what a match means and what the result promises before choosing an algorithm.

Linear search works without sorted input by checking candidates directly. Binary search uses sorted order to discard intervals, giving logarithmic lookup on an array while requiring careful boundary updates. Hash tables, ordered trees, and graph traversals address different organizations and questions.

When choosing an approach, account for preparing and updating the data as well as the query itself. A correct search finds the requested answer or has a clear reason why no candidates remain.

This post is licensed under CC BY 4.0 by the author.