AP® Computer Science A glossary

Linear search

Also called: sequential search

Course: AP® Computer Science A Shows up in: Unit 4: Data Collections

A search algorithm that checks each element in order until it finds the desired value or has checked every element.

Appears in the course and exam description (CED): 4.14.A.14.14.A.2

Linear search works on any array or ArrayList, sorted or not, and can start from either end. On a 2D array it searches each row in turn. A search method usually returns the index of the target, or -1 when the target is not found. In the worst case it checks every element.

Example

public static int find(int[] arr, int target)
{
    for (int i = 0; i < arr.length; i++)
    {
        if (arr[i] == target)
        {
            return i;
        }
    }
    return -1;
}
Learn it properly, with a checkpoint 4.14 Searching Algorithms

Related terms

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure