ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.14

Searching Algorithms

Skill 2.BSkill 3.BSkill 4.A

Big idea: Linear search checks elements one at a time until it finds the target or runs out. It works on any data, sorted or not.

Learning objectives
  • Develop code used for linear search algorithms to search for specific information in a collection and determine the results of executing a search.

Linear search returning an index

Methods
static int indexOf(int[] arr, int target) {
  for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) {
      return i;
    }
  }
  return -1;   // only after checking every element
}
Using them
System.out.println(indexOf(new int[] {4, 7, 1, 7}, 7));
System.out.println(indexOf(new int[] {4, 7, 1, 7}, 9));
Output
1
-1

Searching objects and 2D arrays

Use equals for objects. For a 2D array, search row by row.

Code
String[][] grid = { {"ox", "cat"}, {"dog", "eel"} };
String target = "dog";
int foundR = -1, foundC = -1;
for (int r = 0; r < grid.length; r++) {
  for (int c = 0; c < grid[r].length; c++) {
    if (grid[r][c].equals(target)) {
      foundR = r;
      foundC = c;
    }
  }
}
System.out.println(foundR + "," + foundC);
Output
1,0
Key points
  • Linear search checks each element in order until it finds the target or reaches the end. It can start at either end.
  • In the worst case it looks at every element.
  • For 2D arrays, linearly search each row.
Watch out
  • Return -1 after the loop, not in an else inside it.
Quick check
Searching {5, 3, 8} for 8 from the front, how many elements are checked?
Show answer
3.